tags:

views:

8837

answers:

6

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.

+9  A: 

Take a look at the Activator.CreateInstance method.

Matt Hamilton
+3  A: 

I've used this successfully:

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

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

R4Y
hm.. turns out usernames aren't unique.
Ray
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.
MusiGenesis
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.
R4Y
A: 

My question should probably have been more specific I actally 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.

PeteT
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.
Jason Jackson
+1  A: 

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.

Jay Bazuzi
A: 

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 RepoerClass();

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.

Asish
A: 

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.

Greg Osborne