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.
 
Back
Top