How to compare instances of record and class in C#
Default behaviour - overview
public class OrderClass { public int Id { get; set; } public string CustomerName { get; set; } }
public record OrderRecord(int Id, string CustomerName);
var c1 = new OrderClass { Id = 1, CustomerName = "Jan" };
var c2 = new OrderClass { Id = 1, CustomerName = "Jan" };
var r1 = new OrderRecord(1, "Jan");
var r2 = new OrderRecord(1, "Jan");
// CLASS - reference comparison
Console.WriteLine(c1 == c2); // false
Console.WriteLine(c1.Equals(c2)); // false
Console.WriteLine(ReferenceEquals(c1, c2)); // false
// RECORD - value comparison
Console.WriteLine(r1 == r2); // true
Console.WriteLine(r1.Equals(r2)); // true
Console.WriteLine(ReferenceEquals(r1, r2)); // false - they are STILL different objects in memory!
The key observation: ReferenceEquals always checks the identity of the object in memory, whether it is a class or a record - record doesn't change what physically happens in memory, it only overrides what Equals()/== do.
Three ways of comparing - and which apply to which type
1. ReferenceEquals() - always an identity comparison, regardless of type
object.ReferenceEquals(c1, c2); // false - different objects in memory (applies to BOTH class and record)
object.ReferenceEquals(r1, r1); // true - to TEN SAM obiekt
This is the only way that always works identically, whether you have a class or a record - because it checks physical identity in memory, ignoring any overridden Equals logic.
2. Equals() - depends on what the given class/record defines
c1.Equals(c2); // false for a plain class (inherits Equals from object = reference equality)
r1.Equals(r2); // true for a record (the compiler generated a value-based Equals)
3. The == operator - for class by default the same as ReferenceEquals, for record the same as Equals
c1 == c2; // false - for a plain class, == is an alias for ReferenceEquals (unless you overload the operator)
r1 == r2; // true - a record AUTOMATICALLY overloads == so that it calls Equals (value comparison)
How to make a class compare like a record - overriding Equals/GetHashCode
If you want value equality for a plain class (without switching to record, e.g. because you need mutability AND comparison by value), you have to write it by hand:
public class OrderClass : IEquatable<OrderClass>
{
public int Id { get; set; }
public string CustomerName { get; set; }
// Nadpisanie Equals(object) - wymagane, dziedziczone z object
public override bool Equals(object obj) => Equals(obj as OrderClass);
// IEquatable<T>.Equals - bardziej wydajne (bez boxing/rzutowania), dobra praktyka
public bool Equals(OrderClass other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true; // optymalizacja - ten sam obiekt
return Id == other.Id && CustomerName == other.CustomerName;
}
// GetHashCode MUST be consistent with Equals - if Equals returns true, the hash MUST be identical
public override int GetHashCode() => HashCode.Combine(Id, CustomerName);
// Overloading the == and != operators - so that they behave like Equals
public static bool operator ==(OrderClass left, OrderClass right)
=> left is null ? right is null : left.Equals(right);
public static bool operator !=(OrderClass left, OrderClass right) => !(left == right);
}
var c1 = new OrderClass { Id = 1, CustomerName = "Jan" };
var c2 = new OrderClass { Id = 1, CustomerName = "Jan" };
c1 == c2; // NOW true - because we overloaded the operator
c1.Equals(c2); // true
This is exactly the code that record generates for you automatically - you can now see the "price" of this convenience: for a class you have to write it by hand (and remember about GetHashCode, IEquatable<T>, operator overloading), for a record you get it for free from a single line.
The key rule: Equals and GetHashCode MUST be consistent
This is a classic trick question in an interview - if you override Equals(), you must also override GetHashCode(), otherwise you break the contract:
// ❌ ERROR - Equals overridden, GetHashCode NOT
public class Order
{
public int Id { get; set; }
public override bool Equals(object obj) => obj is Order o && o.Id == Id;
// NO GetHashCode() - the compiler gives a WARNING (CS0659), but it compiles
}
The practical consequence - this breaks HashSet/Dictionary:
var order1 = new Order { Id = 1 };
var order2 = new Order { Id = 1 };
order1.Equals(order2); // true - "logicznie" to ten sam order
var set = new HashSet<Order>();
set.Add(order1);
set.Contains(order2); // MAY return false! - because GetHashCode() inherited from object
// gives DIFFERENT hashes for order1 and order2 (since they are different objects in memory),
// so the HashSet looks in the WRONG "bucket" and never finds a match
record always generates a consistent Equals/GetHashCode pair, so this particular bug is impossible in records - it is one of the real, practical advantages, not just syntactic convenience.
Comparing collections - record vs class in LINQ
var records1 = new List<OrderRecord> { new(1, "Jan"), new(2, "Anna") };
var records2 = new List<OrderRecord> { new(1, "Jan"), new(2, "Anna") };
records1.SequenceEqual(records2); // true - compares element by element via Equals (by value)
var classes1 = new List<OrderClass> { new() { Id = 1 }, new() { Id = 2 } };
var classes2 = new List<OrderClass> { new() { Id = 1 }, new() { Id = 2 } };
classes1.SequenceEqual(classes2); // false - because Equals for a class is reference equality, the objects are different
Comparing records with inheritance - the exact type is taken into account
public record Animal(string Name);
public record Dog(string Name, string Breed) : Animal(Name);
Animal a = new Dog("Rex", "Labrador");
Animal b = new Animal("Rex"); // TYLKO Animal, nie Dog
a.Equals(b); // false - although Name="Rex" matches, the RUNTIME TYPE differs (Dog vs Animal)
This is a difference compared to a "naive" hand-written Equals in a class, where you have to remember to check the type yourself (obj is Order o), and with inheritance it is easy to get wrong - record does it correctly automatically through the generated EqualityContract property.
IEqualityComparer<T> - custom comparison, independent of the class's Equals/GetHashCode
Sometimes you want to compare objects differently from the class's default behaviour - then instead of overriding Equals on the class itself, you create a separate comparer:
public class OrderByIdComparer : IEqualityComparer<OrderClass>
{
public bool Equals(OrderClass x, OrderClass y) => x?.Id == y?.Id; // comparison ONLY by Id
public int GetHashCode(OrderClass obj) => obj.Id.GetHashCode();
}
var set = new HashSet<OrderClass>(new OrderByIdComparer());
This works identically for record and class - IEqualityComparer<T> is an external mechanism, independent of how the type itself defines its "default" equality.
Summary table
| Comparison method | class (default) |
record (default) |
After a manual override in a class |
|---|---|---|---|
ReferenceEquals() |
Identity in memory | Identity in memory | Identity in memory (unchanged) |
Equals() |
Identity (= ReferenceEquals) |
Value of all fields | Value (if you implement it that way) |
== |
Identity (alias for ReferenceEquals) |
Value (through the generated Equals) |
Value (if you overload the operator) |
GetHashCode() |
Based on identity (the default from object) |
Based on the field values | You have to match it to Equals by hand |
Practical interview advice
"By default a
classcompares by reference, arecordby the value of all properties - this follows from the compiler automatically generatingEquals/GetHashCode/the==/!=operators for records. If I need value equality for aclass(e.g. because I have to keep mutability, which arecordwithinitdoesn't give), I implementIEquatable<T>by hand, remembering the key rule:EqualsandGetHashCodemust be consistent, otherwise behaviour inHashSet/Dictionarybreaks.ReferenceEqualsalways stays unchanged - it checks physical identity in memory, regardless of type."