Default value of a type at Runtime

viky picture viky · Mar 22, 2010 · Viewed 89.6k times · Source

For any given type i want to know its default value.

In C#, there is a keyword called default for doing this like

object obj = default(Decimal);

but I have an instance of Type (called myType) and if I say this,

object obj = default(myType);

it doesn't work

Is there any good way of doing this? I know that a huge switch block will work but thats not a good choice.

Answer

Dean Harding picture Dean Harding · Mar 22, 2010

There's really only two possibilities: null for reference types and new myType() for value types (which corresponds to 0 for int, float, etc) So you really only need to account for two cases:

object GetDefaultValue(Type t)
{
    if (t.IsValueType)
        return Activator.CreateInstance(t);

    return null;
}

(Because value types always have a default constructor, that call to Activator.CreateInstance will never fail).