Saturday, June 25, 2011

Some facts about Null in .NET

As I am tweeting around the facts on Nulls for last couple of days, I thought of writing a blog on that as many of you have already requested me on this regard. This post is basically dealing with Nulls and will go through only with basic C# stuffs, so for geeks, it is not recommended and you might end up knowing a little or almost nothing. So if you just here for time pass, then I refer to read on.

Considering the fact Nulls appear on any objects, we have mainly two categories of programmable storage in .NET.

  1. Nullables (generally mutable with exceptions like strings)
  2. Value Types / struct (generally immutable)
Nullables are types that either user defined or in framework in which one of its value can be null. .NET treats null specially. Say for instance :



class Program
    {
        static void Main(string[] args)
        {
            X xobj = null;
            Y yobj = null;

           
        }
    }

Here both xobj and yobj holds null, but you cannot equate xobj == yobj. It is illegal.

Another important fact is Unassigned local values are not treated as null. .NET compiler throws exception when an unassigned variable is used. But if you declare the member of a class unassigned, it will automatically be assigned to null. Hence :

static void Main(string[] args)
        {
            X xobj;
            Y yobj = null;

            xobj = xobj ?? new X();


        }

Throws exception while :
public class X
    {
        Y yobj;

        public X()
        {
            yobj = yobj ?? new Y();
        }
    }
    public class Y
    {
    }


And it does not throw any exception.

Note : If you don’t remember ?? in the above code, then it’s the new Null Coalesce Operator which assigns the value on the right when value on the left is null.

Another important thing that comes with Nulls are Nullable value types. We can use Nullable where T is a struct easily to interface a valuetypes to take nulls.


int x = 0;
int? x = null;

Where int? is a short form for Nullable. Cool huh. Nullable object contains two properties, HasValue which indicates whether the object is assigned to any value. It returns false when the value is null, and Value which holds the value. The value returns default(int) when the HasValue is false.

NullReferenceException

Yes, while working with .NET one of the message that you see the most in your code is “Object reference is not set to an instance of object”. Well, its actually a message coming from NullReferenceException, and you can do nothing with it. When your code encounters a NullReferenceException it does not hold the call stack or even the actual object that generates the exception, so there is nothing we can do with it.

Say for instance,

X x1= null;
Console.WriteLine(x1.ToString());

Here ToString cannot be evaluated on Nulls, and hence throws NullReferenceException. So be careful to check your code full proof so that the value x1 cannot be null.

Null follows object hierarchy:

Well, 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.

Note: If you overload the call method with a method which takes an object Z which does not belong to family of X, the call to the method Call would produce a compiler error saying about ambiguity.

.NET nulls are very vital. Programmers generally try to avoid it but at times, it is the most important value for an object. Any object derived from the family ValueType is not nullable, but other than that most of the others are nullable.

That’s all folks.

Happy Coding.

No comments:

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!