I’ve inherited some code and it is making me cringe when I look at it. Is there more elegant way to write the following?
Dim myItem As DTO.MyBaseClass = Nothing
Dim myType As String = GetTypeString()
Select Case myType
Case Is = "Case1"
myItem = Bus.BusManager(Of DTO.MyClass1).Read()
Case Is = "Case2"
myItem = Bus.BusManager(Of DTO.MyClass2).Read()
'... etc etc for 30 lines
Is there a way to make a map from the string to the class type and then just have a line like so? Or something similar?
myItem = Bus.BusManager(Of MappingDealy(myType)).Read()
Since
BusManageris a Generic, the type you pass intoOf <type>must be specified at compile time. It’s not like a traditional parameter that you can change at runtime.It’s unclear from the code you listed what
BusManageractually does. If all it’s doing is creating an instance of the Generic type, then maybe the person who created it doesn’t really understand generics. Do you have the ability to rework howBusManagerworks, or are you limited to using it as is?As @jmoreno mentioned, you can use reflection to create an instance of a type from a string containting the name of the type. Here’s how that would work:
In a production app, I’d probably set the return type for all of these methods to my base class or interface. Just make sure you pass in the full
typeNameincluding the Namespace.With that factory class in place, then the elegant version of your code would look something like this: