I have a base abstract class with several classes that extend and override it, however they all have the same constructor. Right now, I am invoking every constructor from the switch statement:
case 1: return new A(arg1);
etc., for about 10 classes. Is there a way with generics or delegates to make one method that will take a class name and create an instance of this type with arguments?
This will help, because if I make changes to the constructors, I must also change each creation.
The delegate will be most frank, but the study does not talk about the appointment of constructors to delegates.
Addition: I am now on wifi with my laptop, and not just with my cell, so here comes some code.
This is an example of what is happening now:
switch (new Random().Next(4)) { case 3: // classA : baseClass, args{int, bool, otherClass} return new classA(arg1, arg2, arg3); case 2: // classB : baseClass, args{int, bool, otherClass} return new classB(arg1, arg2, arg3); case 1: // classC : baseClass, args{int, bool, otherClass} return new classC(arg1, arg2, arg3); case 0: // classD : baseClass, args{int, bool, otherClass} return new classD(arg1, arg2, arg3); default: continue; }
I would like to name one instance at the end of the block with three arguments.
The solution I was thinking about is the make and instantiator class, which works something like this:
ClassInstantiator inst = new ClassInstantiator(arg1, arg2, arg3); switch(new Random().Next(4)) { case 4: return inst.instantiate<classA>(); ... }
Is it already built into the language, or does anyone know a more elegant solution?