Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create default instance of type [duplicate]

What is the reflective equivalent of :

default(object);  //null

When I do not have the type until runtime, e.g.

public void Method(Type type)
{
   var instance = type.CreateDefault(); //no such method exists, but I expect there is a way of doing this?
} 
like image 563
Myles McDonnell Avatar asked Apr 27 '12 13:04

Myles McDonnell


1 Answers

For any reference type, the default value is a null instance. For any value type, the default value can be obtained via Activator.CreateInstance. But when you have a variable called instance that suggests you want an actual instance rather than a null reference... So while you can do this:

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

... it's not really clear how useful this is. The is the default value of the type, which isn't the same as a default instance of the type.

like image 185
Jon Skeet Avatar answered Oct 18 '22 15:10

Jon Skeet