Skip to content

Value based equality

Context: Records compare all members for equality, not reference equality. Two record instances are equal if all their properties match.

public record Point(int X, int Y);
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2); // True
Console.WriteLine(ReferenceEquals(p1, p2)); // False

Records override Equals(object) and GetHashCode() to consider all fields/properties. They also implement IEquatable<T>.

Same value semantics, but record struct uses structural equality similar to record class.

Unit testing: Value equality makes assertions simpler because you can compare expected and actual record instances directly without comparing each property.

Example: In xUnit, Assert.Equal(expected, actual) works out of the box for records. No need to write custom equality comparers.