1
Answer

Array of Classes/Types

Ask a question
Positronism

Positronism

17y
2.8k
1

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!


Answers (1)