Generics - Default Objects of Type Parameters


In generics, there are occasions when the differences between reference types and value types are significant. One situation occurs when an object of a type is to be given a default value. For reference types, the default value is null. The default value for a struct is an object of that type in which all the fields have their values set to default values. A problem thus arises when attempting to give a variable of a type parameter a default value. What should be used - null, 0 or some other value for structs?

The solution to the problem comes in the form of another variant of the default keyword. The syntax is as follows.

default(type)

The program below defaults a variable of a type parameter.

// Generic9 - Defaulting Objects

using System;

class X { }

class Generic<T>
{
    public T t;

    public Generic()
    {
        t = default(T);
    }
}

class Program
{
    static void Main()
    {
        Generic<X> x = new Generic<X>();

        if (x.t == null) Console.WriteLine("x.t is null");

        Generic<int> y = new Generic<int>();

        if (y.t == 0) Console.WriteLine("y.t is 0");
    }
}

The output of the program is shown below.

x.t is null
y.t is 0