Sunday, January 29, 2012

Did you know the two uses of ‘default’?

Well, maybe you do and maybe you don’t. And I’m not trying to start a series of posts tagged “Did you know?”, I guess Sara Ford is much better at it.

You’ve used the default keyword in C# as many times as possible in switch statements to indicate the default operation to be carried out. That’s one place where you would normally use the default keyword.

You can also use the default keyword in generic code where it specifies the default value of the type parameter which is null for reference types and zero for value types. In generic programming it is always difficult to guess what default value to assign to a parameterized type T when you don’t know information such as whether T is a value/reference type; if it’s a value type, is it an elementary type or a struct? This is where the default keyword is used to find out the exact default value for the current type. Here is how it would be used:

class MyGenerics<T>
{
    public void MyMethod()
    {
        T myVar = default(T);
     
        //...
        //...
        int defaultValue = default(int);
    }
}

The default value for reference types is null, for value types is zero and for struct types each member is initialized with it’s default value depending on whether it is a value or reference type.

No comments:

Post a Comment