views:

78

answers:

1

So given a static type in your code you can do

var defaultMyTypeVal = default(MyType);

How would you do the same thing given a variable of Type so you can use it during runtime?

In other words how do I implement the following method without a bunch of if statements or using Generics (because I will not know the type I'm passing into the method at compile time)?

public object GetDefaultValueForType(Type type) {
  ....
}
+9  A: 

From this post:

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