Hi,
Say if I define a number of classes: myClass1, myClass2, myClass3 and so on. Is it possible to put these classes (not the instance/object of the class) into a dictionary or array or something so that I can define an object of specific type later on?
Just to clarify, I'm looking for something like:
arrayOfClasses[3] = [myClass1,myClass2,myClass3];
//chunks of code here
arrayOfClasses[i] myObject = new arrayOfClasses[i]();
This is to save trouble of doing something like this:
switch (i) {
case 1:
myClass1 myObject = new myClass1();
break;
case 2:
myClass2 myObject = new myClass2();
break;
case 3:
myClass3 myObject = new myClass3();
break;
}
which is going to be a pain if there are hundreds of different classes to choose from.
Thanks!
AlanPosted Aug 26, 2007, 5:13 AM
Whilst you can't do that, you can do this:
string[] arrayOfClassNames = new string[3]{"myClass1", "myClass2", "myClass3"};
// create an object of type myClass2, say, which corresponds to an index of 1
object temp = Activator.CreateInstance(Type.GetType(arrayOfClassNames[1]));
myClass2 mc2 = (myClass2)temp;
If you need to assign a reference to the object to a variable of type myClass2, which would usually be the case, then there's no way to avoid hardcoding the cast AFAIK.