Search code examples
c#enumssubclassing

Best way to decide which subclass is needed


I am working on a large-scale checkout application for a current project. This checkout has many cases depending on the user's admin level, how they got to the checkout, and what type of item they are checking out, and so the process is abstracted away from the .aspx pages via a set of context classes.

These classes all subclass from a single class, CheckoutContext, and the type of class to be used is noted via an enum.

Is there something similar to typedef I can use to choose which subclass to use, or should I simply have a method that returns the relevant class, like so:

CheckoutContext chooseSubclass(CheckoutCase c)
{
CheckoutContext output;
switch (c):
{
  case CheckoutCase.SingleItemNew:
    output = new SingleItemNew;
    break;
  case . . . 
  return output;
}
}


Solution

  • If there are a large number of cases, I would create a Dictionary<CheckoutCase, Type> and populate it one time with the set of all CheckoutCase values and corresponding CheckoutContext Types. Then you could use Activator.CreateInstance to return the appropriate type instead of a gigantic switch statement.