+ 1

Can i use generics.....?

in my program, i have several classes which are all inherited from the same base, they are very similar, and all have the same methods. I would like the program to create an instance of the different classes depending on user choice, but I dont want to make very long swich statements.... usuario ir possible ti use generics instead so in the case statement i just asign the Kind of object and out of it i calle the different methods?? thank You

3rd Jun 2017, 8:50 AM
Jorge Casas
Jorge Casas - avatar
2 Answers
+ 1
Hey Jorge, generics won't help you here as you can not pass the generic class by string. I'd recommend you to use a dicionary which has the user choice as key and an anonymous function which returns a new object of the class, as the value. Then you can just call those more or less dynamically. Example: https://code.sololearn.com/c4SAq6oynyyC/?ref=app
23rd Jun 2017, 10:55 PM
LaserHydra
LaserHydra - avatar
+ 1
Reflection may also be a solution but to be honest, it's sometimes best to keep it simple. Don't sacrifice readability and time into something trivial. If it's only several classes, you don't need to overcomplicate the solution.
7th Mar 2018, 1:23 PM
Greg R Taylor
Greg R Taylor - avatar