Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to find the default value for a run-time Type? [duplicate]

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) {
  ....
}
like image 663
George Mauer Avatar asked Jun 09 '10 20:06

George Mauer


1 Answers

From this post:

public object GetDefaultValue(Type t)
{
    if (t.IsValueType) {
        return Activator.CreateInstance(t);
    } else {
        return null;
}
like image 128
SwDevMan81 Avatar answered Oct 09 '22 00:10

SwDevMan81