Advertisement
Advanced C#, Equality: Equals, GetHashCode & IEquatable

How does record type equality work by default, and how does it differ fundamentally from a regular class's default equality?

Short answer

Unlike a regular class (reference equality by default), a record automatically generates VALUE-based Equals(), GetHashCode(), and == operator overloads based on ALL its properties — two record instances with identical property values are considered equal, without you writing any…

Save C# mock interview
Advertisement
AModel answer
Unlike a regular class (reference equality by default), a record automatically generates VALUE-based Equals(), GetHashCode(), and == operator overloads based on ALL its properties — two record instances with identical property values are considered equal, without you writing any equality code yourself.
public record Point(int X, int Y);
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2);       // True -- value equality, auto-generated
Console.WriteLine(p1.Equals(p2));  // True
Real-world example
Relying on a record's automatically-generated value equality for a DTO or value object without writing manual Equals()/GetHashCode() overrides.
Likely follow-ups
  • How would you override just ONE property's contribution to a record's auto-generated equality, if needed?
Related topics