Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why casting to object when comparing to null?

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 ?

like image 929
Thibault Falise Avatar asked Aug 04 '10 15:08

Thibault Falise


2 Answers

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

like image 184
Paul Ruane Avatar answered Sep 21 '22 21:09

Paul Ruane


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

like image 26
Steven Avatar answered Sep 17 '22 21:09

Steven