Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

((System.Object)p == null)

Why do this:

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

Instead of this:

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

I don't understand why you'd ever write ((System.Object)p)?

Regards,

Dan

like image 818
Daniel James Bryars Avatar asked May 25 '10 21:05

Daniel James Bryars


2 Answers

You cast to object when you don't know or can't be sure whether the original class has overridden operator ==:

using System;
class AlwaysEqual
{
    public static bool operator ==(AlwaysEqual a, AlwaysEqual b)
    {
        return true;
    }

    public static bool operator !=(AlwaysEqual a, AlwaysEqual b)
    {
        return true;
    }
}


class Program
{
    static void Main()
    {
        object o = new AlwaysEqual();
        AlwaysEqual ae = o as AlwaysEqual;

        if (ae == null)
        {
            Console.WriteLine("ae is null");
        }

        if ((object)ae == null)
        {
            Console.WriteLine("(object)ae is null");
        }
    }
}

This code outputs only "ae is null", which is obviously not the case. The cast to object avoids the AlwaysEqual class's operator == and is therefore a true reference check against null.

like image 53
Mark Rushakoff Avatar answered Oct 03 '22 13:10

Mark Rushakoff


Every object in .NET is derived from System.Object so there is no need for explicit cast.

like image 44
šljaker Avatar answered Oct 03 '22 11:10

šljaker