Create default instance

What is the reflective equivalent:

default(object); //null 

When I have no type before execution, for example

 public void Method(Type type) { var instance = type.CreateDefault(); //no such method exists, but I expect there is a way of doing this? } 
+6
source share
1 answer

For any reference type, the default value is a null instance. For any type of value, the default value can be obtained using Activator.CreateInstance . But when you have a variable called instance that assumes you need the actual instance, not a null reference ... Therefore, when you can do this:

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

... it's not entirely clear how useful this is. This is the default value for the type, which does not match the default instance for the type.

+10
source

Source: https://habr.com/ru/post/914336/


All Articles