Alex Rivera | Logout

Default value of a type at Runtime

Asked 2010-03-22T05:55:37.647
186

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.

Edit
Report

2 Answers

316

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).

answered 2010-03-22T06:04:27.893
2

What do you mean by "Default Value"? All reference Types ("class") have null as default value, while all value types will have their default values according to this table.

answered 2010-03-22T06:04:58.240

Your Answer