Class name as a string variable

A

ADi

Hello,

I'm wondering it is possible somehow in C# to make that operation
possible:

abstract class ParentClass { };
class ClassA : ParentClass { };
class ClassB : ParentClass { };
class ClassC : ParentClass { };

ParentClass object; // declare an abstract object

string[] Classes = new String[] { "ClassA", "ClassB", "ClassC" };

object = new Classes[0](); // defining "ClassA" object
^^^^^^^^^^

....in other words, how to make object which name is given as string
variable? It's possible AT ALL?



Regards,
ADi
 
M

Marina

You have to use reflection. Check out System.Reflection namespace. And also,
just do a search on Google. You will find tons of sample code.
 
J

Jon Skeet [C# MVP]

ADi said:
I'm wondering it is possible somehow in C# to make that operation
possible:

abstract class ParentClass { };
class ClassA : ParentClass { };
class ClassB : ParentClass { };
class ClassC : ParentClass { };

ParentClass object; // declare an abstract object

string[] Classes = new String[] { "ClassA", "ClassB", "ClassC" };

object = new Classes[0](); // defining "ClassA" object
^^^^^^^^^^

...in other words, how to make object which name is given as string
variable? It's possible AT ALL?

I think you're looking for Activator.CreateInstance and possibly
Type.GetType as well.
 
A

ADi

Thnx for the clue, System.Reflection is exactly what I need... :)

thanks again ;)

Regards,
ADi.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top