Object hierarchy of NULL

By | July 8, 2011

It is interesting that Nulls actually follows object hierarchy. That means the object of a class which is the most derived is taken to be more nullable than its base.

Say for instance,

class Program
    {

        static void Main(string[] args)
        {
            MyClass mclass = new MyClass();
            mclass.Call(null);

            Console.Read();
        }

        
    }

    public class MyClass
    {
        public void Call(X x1)
        {
            Console.WriteLine("Called X1");
        }
        public void Call(Y y1)
        { 
            Console.WriteLine("Called Y1");
        }
        public void Call(object x)
        {
            Console.WriteLine("Called object");
        }
    }

    public class X
    {

    }
    public class Y : X
    {

    }

The output will be “Called Y1” as you can see Y is the most derived class.

Hence you can say, nulls are more prone to more nullables. If you have not defined the overload with Y, it would have called X, and finally it would have taken object.