In .NET, at runtime: How to get the default value of a type from a Type object?

Néstor Sánchez A. picture Néstor Sánchez A. · Apr 21, 2010 · Viewed 15.2k times · Source

Possible Duplicate:
Default value of a type

In C#, to get the default value of a Type, i can write...

var DefaultValue = default(bool);`

But, how to get the same default value for a supplied Type variable?.

public object GetDefaultValue(Type ObjectType)
{
    return Type.GetDefaultValue();  // This is what I need
}

Or, in other words, what is the implementation of the "default" keyword?

Answer

michalburger1 picture michalburger1 · Apr 21, 2010

I think that Frederik's function should in fact look like this:

public object GetDefaultValue(Type t)
{
    if (t.IsValueType)
    {
        return Activator.CreateInstance(t);
    }
    else
    {
        return null;
    }
}