Junior — Middle
In what cases is a comparison of reference data types performed?
sobes.tech AI
Answer from AI
In C#, comparison of reference types is performed in the following cases:
-
ReferenceEquals comparison — checks whether two variables refer to the same object in memory.
-
Overriding Equals() — for comparing the contents of objects rather than their addresses.
-
Operators == and != — by default, compare references for reference types, but can be overloaded to compare contents.
Example:
class Person {
public string Name;
public override bool Equals(object obj) {
if (obj is Person other) {
return this.Name == other.Name;
}
return false;
}
public override int GetHashCode() => Name.GetHashCode();
}
var p1 = new Person { Name = "Alice" };
var p2 = new Person { Name = "Alice" };
bool areSameReference = Object.ReferenceEquals(p1, p2); // false
bool areEqual = p1.Equals(p2); // true
Thus, comparison of reference types is either for checking if variables refer to the same object or for comparing the contents of objects if the Equals method is overridden.