What is the use of `default` keyword in C#?

Solution 1:

The default keyword is contextual since it has multiple usages. I am guessing that you are referring to its newer C# 2 meaning in which it returns a type's default value. For reference types this is null and for value types this a new instance all zero'd out.

Here are some examples to demonstrate what I mean:

using System;

class Example
{
    static void Main()
    {
        Console.WriteLine(default(Int32)); // Prints "0"
        Console.WriteLine(default(Boolean)); // Prints "False"
        Console.WriteLine(default(String)); // Prints nothing (because it is null)
    }
}

Solution 2:

You can use default to obtain the default value of a Generic Type as well.

public T Foo<T>()
{
    .
    .
    .
    return default(T);
}

Solution 3:

The most common use is with generics; while it works for "regular" types (i.e. default(string) etc), this is quite uncommon in hand-written code.

I do, however, use this approach when doing code-generation, as it means I don't need to hard-code all the different defaults - I can just figure out the type and use default(TypeName) in the generated code.

In generics, the classic usage is the TryGetValue pattern:

public static bool TryGetValue(string key, out T value) {
    if(canFindIt) {
        value = ...;
        return true;
    }
    value = default(T);
    return false;
}

Here we have to assign a value to exit the method, but the caller shouldn't really care what it is. You can contrast this to the constructor constraint:

public static T CreateAndInit<T>() where T : ISomeInterface, new() {
    T t = new T();
    t.SomeMethodOnInterface();
    return t;
}

Solution 4:

The default keyword has different semantics depending on its usage context.

The first usage is in the context of a switch statement, available since C# 1.0:
http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx

The second usage is in the context of generics, when initializing a generic type instance, available since C# 2.0:
http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

Solution 5:

"default" keyword (apart from switch-case) helps you initialize the instance of an object like class, list and more types. It is used because of its generic property where it helps you to assign the type's default value when you do not know its value in advance as a way to avoid mistakes in your further(future) code.