views:

135

answers:

3

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?

A: 

Instantiate an instance of that type. It will be assigned a value, and that value will be the default value ...

public object GetDefaultValue( Type t )
{
     return Activator.CreateInstance<t>();
}

But, check if it is a reference type first, since the default voor reference types is NULL.

Frederik Gheysels
That won't be the same as default(T) if T is a reference type. The default value for a reference type is null, not a new instance of the class.
Daniel Plaisted
Hmm, I thought that the default keyword could only be used for value types, but apparently, i was wrong.
Frederik Gheysels
+5  A: 

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;
    }
}
Bus
that is!I tested it with struct, enum, value and reference types and works pretty fine.thanks!
Néstor Sánchez A.
A: 

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