Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the default value of a type if the type is only known as System.Type? [duplicate]

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) {   //??? } 
like image 466
Patrick Klug Avatar asked Aug 15 '09 04:08

Patrick Klug


People also ask

What is the default value for reference type data type?

The default value of a reference type is null . It means that if a reference type is a static class member or an instance field and not assigned an initial value explicitly, it will be initialized automatically and assigned the value of null .

What is the default value for an object of type object?

Objects. Variables of any "Object" type (which includes all the classes you will write) have a default value of null.


1 Answers

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.

public static object GetDefaultValue(Type type) {    return type.IsValueType ? Activator.CreateInstance(type) : null; } 

Edit: Jon is (of course) correct. IsClass isn't exhaustive enough - it returns False if type is an interface.

like image 135
Mark Brackett Avatar answered Sep 20 '22 14:09

Mark Brackett