0

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:

  1. Use if statements:
    X theObj;
    if (theType=="A") theObj = new X_A();
    else theObj = new X_B();
  1. 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).)

dashnick
  • 2,020
  • 19
  • 34

1 Answers1

1

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.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • But do I have to do this every time I create an object of this type? Id like to have at most 1 if statement in the code.. – dashnick Jun 04 '22 at 01:47
  • 1
    Create a factory method that generates an instance of the type, and you do the selection there. One method, to be used in many places. – John Alexiou Jun 04 '22 at 03:22
  • In that case, should I just make it a generic method? – dashnick Jun 04 '22 at 03:38
  • @dashnick - that is a design choice. If you know at compile time what you want to do the way to do it as as shown above, but if you want the flexibility to choose as runtime then use generics, or just a factory class that generates the object as needed. – John Alexiou Jun 04 '22 at 04:22