I was just looking at the Guidelines for Overloading Equals() on msdn (see code below); most of it is clear to me, but there is one line I don\'t get.
if ((S
The ==
operator may be overridden, and if it is, the default reference comparison may not be what you get. Casting to System.Object ensures that calling ==
performs a reference equality test.
public static bool operator ==(MyObj a, MyObj b)
{
// don't do this!
return true;
}
...
MyObj a = new MyObj();
MyObj b = null;
Console.WriteLine(a == b); // prints true
Console.WriteLine((object)a == (object)b); // prints false
I suppose, since the article also talks about overriding operator==, that it's forcing it to use the == operator defined on Object rather than any overloaded operator in the current class.
I prefer using object.ReferenceEquals(a, b)
in this ambiguous context to force reference comparison because it makes the intent clear while preserving the semantics precisely (in fact, ReferenceEquals
is implemented like that).