Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an instance for a given Type? [duplicate]

Tags:

With generics you can

var object = default(T); 

But when all you have is a Type instance I could 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 a shorter way, like the generics version?

like image 348
Jader Dias Avatar asked Apr 11 '11 14:04

Jader Dias


People also ask

How do I create a new instance?

To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.

What is used to create a new instance of a class an object )?

Instantiating a Class The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.

How do you copy an instance class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy. deepcopy(c) then vars(c2) == {'a': 11, 'r': 2} and vars(c) == {'a': 11, 'r': 2} but the traceback your are reporting wouldn't be produced by the class definition you gave...


1 Answers

The closest available is Activator.CreateInstance:

object o = Activator.CreateInstance(type); 

... but of course this relies on there being a public parameterless constructor. (Other overloads allow you to specify constructor arguments.)

I've used an explicitly typed variable here to make it clear that we really don't have a variable of the type itself... you can't write:

Type t = typeof(MemoryStream); // Won't compile MemoryStream ms = Activator.CreateInstance(t); 

for example. The compile-time type of the return value of CreateInstance is always object.

Note that default(T) won't create an instance of a reference type - it gives the default value for the type, which is a null reference for reference types. Compare that with CreateInstance which would actually create a new object.

like image 178
Jon Skeet Avatar answered Oct 20 '22 21:10

Jon Skeet