C# Interview Question #101
What is the difference between reference equality and value equality in C#?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
Reference equality checks whether two reference variables point to the same object instance. Value equality checks whether two objects represent the same logical value.
Detailed Explanation
Reference equality checks whether two reference variables point to the same object instance. Value equality checks whether two objects represent the same logical value.
For normal classes, object.ReferenceEquals can be used to test identity. Classes can override Equals and GetHashCode or implement IEquatable<T> to provide value-based equality. Records provide value-based equality by default.
When equality is customized, Equals and GetHashCode must remain consistent, especially when objects are used as keys in Dictionary or elements in HashSet.
Code Example
var p1 = new Product { Id = 1 };
var p2 = p1;
bool sameReference = ReferenceEquals(p1, p2); // true