Junior — Middle
Millistel juhtudel tehakse viidetüüpide võrdlust?
sobes.tech AI
Vastus AI-lt
In C#, the comparison of reference types occurs in the following cases:
-
ReferenceEquals comparison — checks whether two variables point to the same object in memory.
-
Overriding Equals() — used to compare the content of objects, not their addresses.
-
== and != operators — by default, for reference types, they compare references, but they can be overridden for content comparison.
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
Therefore, comparison of reference types is performed either to check if variables refer to the same object, or to compare the content of objects if the Equals method is overridden.