17

While browsing the MSDN documentations on Equals overrides, one point grabbed my attention.

On the examples of this specific page, some null checks are made, and the objects are casted to the System.Object type when doing the comparison :

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);
}

Is there a specific reason to use this cast, or is it just some "useless" code forgotten in this example ?

5 Answers 5

15

It is possible for a type to overload the == operator. The cast to object ensures that the original definition is used.

0
15

As others said, the type might override the == operator. Therefore, casting to Objectis equivalent to if (Object.ReferenceEquals(p, null)) { ... }.

2
  • 4
    +1 Using ReferenceEquals is clearer to me than the cast to object
    – Justin
    Aug 4, 2010 at 15:33
  • +1 The intent is more clearly shown by using ReferenceEquals. Aug 4, 2010 at 16:41
7

I believe casting to System.Object would get you around any operator overloading that TwoDPoint might have.

1

It likely exists to avoid confusion with an overloaded == operator. Imagine if the cast did not exist and the == operator was overloaded. Now the p == null line would potentially bind to the operator ==. Many implementations of operator == simply defer to the overridden Equals method. This could easily cause a stack overflow situation

public static bool operator==(TwoDPoint left, TwoDPoint right) {
  return left.Equals(right);
}

public override bool Equals(System.Object obj) {
    ...
    TwoDPoint p = obj as TwoDPoint;
    if ( p == null ) {  // Stack overflow!!!
        return false;
    }

    ...
}

By casting to Object the author ensures a simple reference check for null will occur (which is what is intended).

0

This might have been part of a larger sample where the == operator was overloaded. In that case, using obj == null could have resulted in StackOverflow if TwoDPoint.Equals(object) was invoked as part of the == definition.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.