7

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) {
  ....
}
George Mauer
  • 117,483
  • 131
  • 382
  • 612
  • 1
    I have already answered this issue in the following post: [Determine default value of an arbitrary Type at run time](http://stackoverflow.com/questions/2490244/default-value-of-a-type/7881481#7881481) Hope this helps ... Mark – Mark Jones Oct 24 '11 at 20:41

1 Answers1

11

From this post:

public object GetDefaultValue(Type t)
{
    if (t.IsValueType) {
        return Activator.CreateInstance(t);
    } else {
        return null;
}
Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184