I'm sure I just don't know what to call this, but I'm trying to have a switch in my code to make my objects one of two subtypes, call them X_A
and X_B
, both subtypes of X
. The code switch is a constant / static variable (basically I want to be able to choose between two types of internal database quickly at compile time).
I see 2 options:
- Use if statements:
X theObj;
if (theType=="A") theObj = new X_A();
else theObj = new X_B();
- use reflection (as here)
Type type = typeof(X_A);
X theObj = (X)Activator.CreateInstance(type);
Is there a cleaner way? One like (2) but with static type checking? Maybe compiler directive or something?
(Also, the reason I just don't change the one line of code creating the object is that there are actually several of these made throughout my code, so I don't to change each one.. hence preference for a better version of (2).)