In C#, how can we check reference equality for a type that implements equality operator?
class C
{
public int Val{get;set;}
public static bool operator =
If you mean equality by reference, you may use the Object.ReferenceEquals
static method even if the ==
operator was overloaded for the current type to work otherwise:
Object.ReferenceEquals(obj1, obj2);
What does object "object equality"?
If by "how can we check object equality for a type that implements equality operator?", you actually mean "how can we check object equality for a type that implements IEquatable<T>
", the short answer is...however you want (with some caveats).
The documentation for IEquatable<T> offers some guidelines. You might also want to implement IComparable<T> as well. And if you implement both IEquatable<T>
and IComparable<T>
, it would make sense if your Equals()
method returns true
for all the cases where your CompareTo()
method returns 0, and for your Equals()
method to return false
for all the cases where your CompareTo()
method returns a non-zero value.
Further, you might want to ensure that you properly override ==
and !=
to provide the same behaviour as calling Equals().