Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new object instance from a Type

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.

How do you get a new object instance from a Type?

like image 419
tags2k Avatar asked Aug 03 '08 16:08

tags2k


People also ask

How do I create a new instance of an object?

Answer. 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.

Can we create multiple objects for a class in C#?

csharp. 3) Creating an Array of objects: If you need the multiple numbers of objects of the same class you can create an array of objects.

Which keyword do you use to create a new instance of an object?

Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.


1 Answers

The Activator class within the root System namespace is pretty powerful.

There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

or (new path)

https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

Here are some simple examples:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);  ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType"); 
like image 80
Karl Seguin Avatar answered Oct 07 '22 08:10

Karl Seguin