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).)
CodePudding user response:
If it is at compile time then use a #if
compile-time directive.
#define USE_A
class Foo
{
X NewX()
{
#if USE_A
return new X_A();
#elif USE_B
return new X_B();
#else
throw new NotSupportedException();
#endif
}
}
You can define USE_A
or USE_B
on top of the code in order for the compiler to pick up the correct branch.