Coder Perfect

A string is used to create a class instance.


Is there a method to construct a class instance based on the fact that I know the class name at runtime? In a nutshell, I’d have the class name in a string.

Asked by PeteT

Solution #1

Take a peek at the Activator to see what I mean. The method CreateInstance is used to create a new instance.

Answered by Matt Hamilton

Solution #2

It’s quite straightforward. If your classname is Car and your namespace is Vehicles, then the parameter should be Vehicles.Car, which returns a Car object. You can construct any instance of any class dynamically in this way.

public object GetInstance(string strFullyQualifiedName)
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         

If you have a fully qualified name (for example, Vehicles. Because the Type.GetType (in this case, car) is in another assembly, it will be null. In such circumstances, you must iterate through all assemblies in order to locate the Type. You can do so by using the code below.

public object GetInstance(string strFullyQualifiedName)
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     return null;

If you want to call a parameterized constructor, follow these steps.

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of


Answered by Sarath KS

Solution #3

I’ve had success using this method:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

The resulting object must be cast to the required object type.

Answered by Ray Li

Solution #4

Probably, I should have asked a more explicit query. Because I already had a base class for the string, I was able to solve it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator is a character in the game. The CreateInstance class contains a number of methods for accomplishing the same goal in different ways. I could have made it an object, however the above is more useful in my circumstance.

Answered by PeteT

Solution #5

You can acquire the assembly represented by the name of any class (for example, BaseEntity) and create a new instance of it from another project in the solution:

  var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");

Answered by asd

Post is based on