29

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?

Community
  • 1
  • 1
Néstor Sánchez A.
  • 3,848
  • 10
  • 44
  • 68
  • This is pretty much duplicate of ["Default value of a type"](http://stackoverflow.com/questions/2490244/default-value-of-a-type). Codeka gives a good [answer](http://stackoverflow.com/questions/2490244/default-value-of-a-type/2490274#2490274) which I think will help you. – Simon P Stevens Apr 21 '10 at 21:30
  • return default(ObjectType) doesn't work? – Joseph Yaduvanshi Apr 21 '10 at 21:30

2 Answers2

45

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;
    }
}
michalburger1
  • 594
  • 5
  • 8
16

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;
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900