I order to be able to read files from another project, I'm copying the write code and adjusting it to my need.
I have come to a curios construct that seems really ugly, but I don't know if there is another way to deal with it.
The code looks something like this:
int type = reader.readInt32():
BaseClass p = BaseClass.Instantiate((BaseClassEnum)type);
object.Read(reader);
This code seems nice, and it is, but BaseClass.Instantiate(BaseClassEnum type) method leaves something to be desired.
Basically, it's a giant switch case statement that instantiates a subclass of the baseclass according to the type parameter passed.
Is there some way to avoid switch case here? Can I create a dictionary where I map BaseClassEnum to some kind of class reference that would allow me to call it's constructor? Something like:
Dictionary<int, ???> bindings = new Dictionary<int, ???>(){
{BaseClassEnum1, SubClass1},
{BaseClassEnum2, SubClass2}
}
//...
//Assuming SubClass1 has a constructor SubClass1()
BaseClass p = new bindings[BaseClassEnum1]();
//I could even create a new constructor SubClass(BinaryReader reader) and do
BaseCoass p = new bindings[BaseClassEnum1](reader);
In the end, the code would look something like this:
BaseClass p = new bindings[(BaseClassEnum)reader.ReadInt32()](reader);