This is a mirror of official site: http://jasper-net.blogspot.com/

Some facts about Null in .NET

| Tuesday, June 28, 2011
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.

    Nullables (generally mutable with exceptions like strings)
    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();
        }


Read more: DOT NET TRICKS
QR: some-facts-about-null-in-net.html

Posted via email from Jasper-net

0 comments: