This question already has an answer here:
- Programmatic equivalent of default(Type) 13 answers
If I want a method that returns the default value of a given type and the method is generic I can return a default value like so:
public static T GetDefaultValue()
{
return default(T);
}
Can I do something similar in case I have the type only as a System.Type
object?
public static object GetDefaultValue(Type type)
{
//???
}
Here is how I normally do it. This avoids the whole 'IsValueType' or searching for constructors issues altogether.
Since you really only have to worry about value types (reference types will just be null), you can use
Activator.CreateInstance
to call the default constructor on them.Edit: Jon is (of course) correct.
IsClass
isn't exhaustive enough - it returnsFalse
iftype
is an interface.Without a generic, you can't guarantee that the type has a parameterless constructor, but you can search for one using reflection:
I tried this in a console app, and it returns a "default" instance of the class — assuming it's a class. If you need it to work for reference types as well, you'll need an additional technique.