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

16,046

Solution 1

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;
    }
}

Solution 2

You should probably exclude the Nullable<T> case too, to reduce a few CPU cycles:

public object GetDefaultValue(Type t) {
    if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) {
        return Activator.CreateInstance(t);
    } else {
        return null;
    }
}
Share:
16,046
Néstor Sánchez A.
Author by

Néstor Sánchez A.

I'm a software developer with more than 20 years of experience in consultancy companies about: Banking, Financials (Factoring), Human Resources, OLAP. I had an startup and created my own diagramming software wich was open-sourced. As of july-2017 I'm working for the public sector.

Updated on June 15, 2022

Comments

  • Néstor Sánchez A.
    Néstor Sánchez A. almost 2 years

    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?