C# ‘Default’ Keyword

Most C# (and C, C++, Java and JavaScript developers for that matter) will be aware of the default keyword and its usage in the switch statement:

switch (options)
{
    case 1:
        {
            //do something
            break;
        }
    default:
        {
            //do something
            break;
        }
}

But it also has an additional use in C# in conjunction with Generics and types. Each type in C# has a default value. Value Types have a default value of zero (false for boolean) and reference types have a default type of null We can try a simple example:

int i = default(int); //i is initialised to zero

And then try it in conjunction with Generics:

class DefaultTest<T>
{
    public DefaultTest()
    {
        System.Console.WriteLine("Default for '" + typeof(T) + "' is " + default(T));
    }
}

class Program 
{
    static void Main(string[] args)
    { 
        DefaultTest b = new DefaultTest();  //outputs 'false'
        DefaultTest i = new DefaultTest();  //outputs '0'
        DefaultTest s = new DefaultTest();  //outputs nothing
        DefaultTest S = new DefaultTest();  //outputs nothing
        DefaultTest d = new DefaultTest();  //outputs 0
    }
}

You can read some more on these in this article: http://en.csharp-online.net/Understanding_Generics—The_default_Keyword_in_Generic_Code

 

,
Trackback

no comment untill now

Add your comment now