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

What is the difference between reference equality (==) and value equality (Equals()) for a reference type by default?

Short answer

For a reference type without overrides, both == and the inherited Object.Equals() check REFERENCE equality — whether two variables point to the exact SAME object in memory — not whether their content/data is logically equivalent.

Save C# mock interview
Advertisement
AModel answer
For a reference type without overrides, both == and the inherited Object.Equals() check REFERENCE equality — whether two variables point to the exact SAME object in memory — not whether their content/data is logically equivalent.
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2);       // False -- different objects, same data
Console.WriteLine(p1.Equals(p2));  // False -- same, unless Equals is overridden
Real-world example
Understanding why two 'identical-looking' objects don't compare as equal until you explicitly define value equality.
Likely follow-ups
  • How does this default behavior differ for value types like struct?
Related topics