c# - How to create an instance for a given Type? -


this question has answer here:

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

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -