In c# I can use default(T)
to get the default value of a type. I need to get the default type at run time from a System.Type
. How can I do this?
E.g. Something along the lines of this (which doesn't work)
var type = typeof(int);
var defaultValue = default(type);
For a reference type return null
, for a value type, you could try using Activator.CreateInstance
or calling the default constructor of the type.
public static object Default(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With