Class name as a string variable

  • Thread starter Thread starter ADi
  • Start date Start date
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
 
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.
 
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.
 

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

Back
Top