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 ==(C c1, C c2)
{
return c1.Val == c2.Val;
}
public static bool operator !=(C c1, C c2)
{
return c1.Val != c2.Val;
}
}
class Program
{
public static void Main(string[] args)
{
C c1=new C(){Val=1};
C c2=new C(){Val=1};
Console.WriteLine(c1==c2);//True. but they are not same objects.
//How can I Check that?
Console.Write("Press any key to continue . . . ");
}
}
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 implementIComparable<T>
as well. And if you implement bothIEquatable<T>
andIComparable<T>
, it would make sense if yourEquals()
method returnstrue
for all the cases where yourCompareTo()
method returns 0, and for yourEquals()
method to returnfalse
for all the cases where yourCompareTo()
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().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: