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

1

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) {
  ....
}
Trentontrepan answered 9/6, 2010 at 20:0 Comment(1)
I have already answered this issue in the following post: Determine default value of an arbitrary Type at run time Hope this helps ... MarkStrongroom
W
11

From this post:

public object GetDefaultValue(Type t)
{
    if (t.IsValueType) {
        return Activator.CreateInstance(t);
    } else {
        return null;
}
Wamble answered 9/6, 2010 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.