C #: How to find default value for runtime type?

So you can do the given static type in your code

var defaultMyTypeVal = default(MyType); 

How would you do the same with a type variable to use it at runtime?

In other words, how to implement the following method without a bunch of if statements or using Generics (because I will not know the type that I pass to the method at compile time)?

 public object GetDefaultValueForType(Type type) { .... } 
+6
c # strong-typing
source share
1 answer

From this post:

 public object GetDefaultValue(Type t) { if (t.IsValueType) { return Activator.CreateInstance(t); } else { return null; } 
+10
source share

All Articles