Sobes.tech
Junior — Middle

How is comparison of reference type objects performed if custom comparison methods are not implemented?

sobes.tech AI

Answer from AI

If in C# the reference type does not have its own comparison methods implemented (for example, if the Equals and GetHashCode methods are not overridden), then object comparison by default is based on reference. This means that two objects are considered equal only if they point to the same instance in memory.

Example:

class Person {}

var p1 = new Person();
var p2 = new Person();

bool areEqual = p1.Equals(p2); // false, because they are different objects
bool areSame = Object.ReferenceEquals(p1, p2); // false

var p3 = p1;
bool areSame2 = Object.ReferenceEquals(p1, p3); // true

Thus, without overriding, comparison checks whether the variables refer to the same object.

How is comparison of reference type objects performed… - sobes.tech