c# - How to create an instance for a given Type? -
this question has answer here:
- get new object instance type 12 answers
- programmatic equivalent of default(type) 12 answers
with generics can
var object = default(t); but when have type instance only
constructor = type.getconstructor(type.emptytypes); var parameters = new object[0]; var obj = constructor.invoke(parameters); or even
var obj = type.getconstructor(type.emptytypes).invoke(new object[0]); isn't there shorter way, generics version?
the closest available activator.createinstance:
object o = activator.createinstance(type); ... of course relies on there being public parameterless constructor. (other overloads allow specify constructor arguments.)
i've used explicitly typed variable here make clear don't have variable of type itself... can't write:
type t = typeof(memorystream); // won't compile memorystream ms = activator.createinstance(t); for example. compile-time type of return value of createinstance object.
note default(t) won't create instance of reference type - gives default value type, null reference reference types. compare createinstance create new object.
Comments
Post a Comment