This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Generics and Default Values

When using generics, classes, structs and methods can be created that process data types that are not defined until used. As reference types and value types represent default values differently, it is important to be able to set those defaults correctl

Default Values

When value types and reference types are created with undefined values, the defaults used are quite different. Reference types with no value set default to null. Value types cannot be set to null so instead use default values. For example, integers default to zero and Boolean values are false if not otherwise assigned.

Default values for reference and value types can be demonstrated by executing the following code in a console application:

NB: Three fields are used instead of local variables as the use of unassigned local variables causes compiler errors. The use of private fields that are never assigned causes warnings only.

class Program
    static int defaultInt;
    static bool defaultBool;
    static object defaultObject;

    static void Main(string[] args)
        Console.WriteLine(defaultInt);              // Outputs "0"
        Console.WriteLine(defaultBool);             // Outputs "False"
        Console.WriteLine(defaultObject == null);   // Outputs "True"

When working with generic types, you may need to create a variable of an unknown type and assign it a default value. You cannot simply assign null, as the type may be a value type. Similarly, you cannot choose an arbitrary value and assign it as this may be an invalid value and would not be the standard default value for any reference type. To overcome this problem, you can use the default keyword.

The following code shows a generic method that returns the default value for a generic type. Note that the type parameter is passed to the default keyword within parentheses:

static T GetDefault<T>()
    return default(T);

To demonstrate the method and the default keyword when used with a reference type, execute the following code. The returned object is set to null:

object o = GetDefault<object>();
Console.WriteLine(o == null);       // Outputs "True"

To demonstrate the default keyword for value types, try executing the following code. This generates a default DateTime value of 1 January 0001. The format of the output will vary according to your local operating system settings.

DateTime dt = GetDefault<DateTime>();
Console.WriteLine(dt);              // Outputs "01/01/0001 00:00:00"
27 May 2010