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.
-
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](http://www.codeplex.com/MEF). – Jay Bazuzi Oct 22 '08 at 05:48
8 Answers
Take a look at the Activator.CreateInstance method.

- 200,371
- 61
- 386
- 320
-
16Related with great examples: http://stackoverflow.com/questions/493490/converting-a-string-to-a-class-name – John S. Apr 24 '13 at 14:23
-
Also this post will be relevant as well, as your type needs to be found: http://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null – Brad Parks Aug 23 '13 at 20:48
-
1Examples: http://stackoverflow.com/questions/7598088/purpose-of-activator-createinstance-with-example – profimedica Mar 31 '14 at 09:11
-
4For example: `var driver = (OpenQA.Selenium.IWebDriver)Activator.CreateInstance("WebDriver", "OpenQA.Selenium.Firefox.FirefoxDriver").Unwrap();` – Endy Tjahjono Oct 04 '14 at 04:37
-
2Important note here: .Unwrap() to get past the remoting handle so you can actually do the casts. @Endy - Thanks – Roger Willcocks Jul 20 '15 at 01:31
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);

- 20,027
- 11
- 82
- 86
-
How to use it without casting and how to do the cast __from the given string__?? – TaW Apr 25 '16 at 12:16
-
2@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 http://stackoverflow.com/a/2690661/904521) – Tomer Cagan May 25 '16 at 08:47
-
2Don'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. – Mehdi Dehghani Dec 14 '19 at 10:21
-
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 – Sarath Subramanian Dec 14 '19 at 13:13
-
1I know, there is no need to work in any organization to know about naming conventions though, this convention known as [Hungarian notation](https://en.wikipedia.org/wiki/Hungarian_notation) and it's one of the bad _and deprecated_ naming convention out there. specially for C# – Mehdi Dehghani Dec 15 '19 at 04:36
-
That's fine. Anyhow you will see expected result though using this notation. Its up to the people searching for this answer whether to use `str` or not. Thanks for the note bro @MehdiDehghani – Sarath Subramanian Dec 15 '19 at 07:40
-
@MehdiDehghani The real sad point is that 90% of people did not realised the essence of Hungarian notation: It's not for variable's data types, it's for variable's usage types. Systems Hungarian is depricated, Apps Hungarian is still useful. – CLS Dec 08 '22 at 12:14
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.
-
13I'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. – MusiGenesis Oct 21 '08 at 23:53
-
14I 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. – Ray Li Oct 21 '08 at 23:58
-
4If base class is known, you can use the base class or an interface of it as the argument to pass descendants without reflection. – That Realty Programmer Guy Jan 25 '14 at 09:01
-
3Useful 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 – Harald Coppoolse Dec 08 '14 at 11:08
-
Xaml on click to a new navigation page is the perfect example, I can think of many more. – Oliver Dixon Jan 05 '16 at 19:03
-
3
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.
-
4Instead 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. – Jason Jackson Oct 22 '08 at 00:53
-
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. – Ethel Evans Jan 05 '11 at 22:01
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");

- 854
- 7
- 10
-
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 – Bernesto Mar 02 '22 at 17:21
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.

- 186
- 1
- 10
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.

- 47
- 1
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.

- 7