279

Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.

1
  • You seem to have described the solution you want to implement, but not the problem you're trying to solve. Perhaps you are trying to do something with extensibility, in which case I suggest you check out the Managed Extensibility Framework. Commented Oct 22, 2008 at 5:48

8 Answers 8

183

Take a look at the Activator.CreateInstance method.

Sign up to request clarification or add additional context in comments.

5 Comments

Related with great examples: stackoverflow.com/questions/493490/…
Also this post will be relevant as well, as your type needs to be found: stackoverflow.com/questions/1825147/…
For example: var driver = (OpenQA.Selenium.IWebDriver)Activator.CreateInstance("WebDriver", "OpenQA.Selenium.Firefox.FirefoxDriver").Unwrap();
Important note here: .Unwrap() to get past the remoting handle so you can actually do the casts. @Endy - Thanks
130

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

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

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

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;
 }

Now if you want to call a parameterized constructor do the following

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

instead of

Activator.CreateInstance(t);

7 Comments

How to use it without casting and how to do the cast from the given string??
@TaW - in order to use a class instance you will need to have some knowledge of what it is going to do - otherwise you won't be able to use it. The most common use case for this would be casting to some interface which give you a predefined contract. (This holds unless you're using dynamic code - see stackoverflow.com/a/2690661/904521)
Don't encode the type of the variable in it's name., e.g: there is no need to prefix strFullyQualifiedName with str, fullyQualifiedName will do the job.
The keyword str is used as a part of naming convention for variables. Certain organizations and projects insist to follow this, hence I used. If you would have worked in certain oraganizations/projects, you will know this. As you said without str also it will do the job :) @MehdiDehghani
I know, there is no need to work in any organization to know about naming conventions though, this convention known as Hungarian notation and it's one of the bad and deprecated naming convention out there. specially for C#
|
58

I've used this method successfully:

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

You'll need to cast the returned object to your desired object type.

6 Comments

I'm trying to imagine a scenario where creating the object via class name and then casting it as that type would make any sense at all.
I see what you mean. It seems redundant. If you know the class name, why do you need the dynamic string? One situation could be that your casting to a base class and the string represents descendants of that base class.
If base class is known, you can use the base class or an interface of it as the argument to pass descendants without reflection.
Useful scenario: you only need the serialization interfaces, or any other quite common interface. You won't cast it to the class, but at least to something more than an object
How to do the cast from the given string??
|
27

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

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

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

2 Comments

Instead of responding in the question section, I would suggest you edit your question and note the changes. You will get more/better answers for doing it.
Thanks for posting the specific line of code that worked for you. Sorting through all the CreateInstance overloads and different ways to generate Types was taking me a lot of time, which you saved me.
8

To create an instance of a class from another project in the solution, you can get the assembly indicated by the name of any class (for example BaseEntity) and create a new instance:

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

1 Comment

While others answer the question, this is a great answer that deals with ensuring you have the appropriate assembly if you know a sibling class in my case. Bravo
4

I know I'm late to the game... but the solution you're looking for might be the combination of the above, and using an interface to define your objects publicly accessible aspects.

Then, if all of your classes that would be generated this way implement that interface, you can just cast as the interface type and work with the resulting object.

Comments

3

For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.

Comments

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

why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.

ReportClass report = new ReportClass();

The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass)); is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.

I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass available.

1 Comment

ReportClass could be the base class or interface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.