views:

117

answers:

3

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 ((System.Object)p == null)

or, in the second override

if ((object)p == null)

Why not simply

 if (p == null)

What is the cast to object buying us?

public override bool Equals(System.Object obj)
{
    // If parameter is null return false.
    if (obj == null)
    {
        return false;
    }

    // If parameter cannot be cast to Point return false.
    TwoDPoint p = obj as TwoDPoint;
    if ((System.Object)p == null)
    {
        return false;
    }

    // Return true if the fields match:
    return (x == p.x) && (y == p.y);
}

public bool Equals(TwoDPoint p)
{
    // If parameter is null return false:
    if ((object)p == null)
    {
        return false;
    }

    // Return true if the fields match:
    return (x == p.x) && (y == p.y);
}
+2  A: 

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.

tvanfosson
+8  A: 

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
Michael Petrotta
+2  A: 

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).

Konrad Rudolph