Search code examples
c#design-patternsenumspolymorphismstrategy-pattern

Polymorphic Enums for state handling


how do i handle Enums without using switch or if statements in C#?

For Example

enum Pricemethod
{
    Max,
    Min,
    Average
}

... and i have a class Article

 public class Article 
{
    private List<Double> _pricehistorie;

    public List<Double> Pricehistorie
    {
        get { return _pricehistorie; }
        set { _pricehistorie = value; }
    }

    public Pricemethod Pricemethod { get; set; }

    public double Price
    {
        get {
            switch (Pricemethod)
            {
                case Pricemethod.Average: return Average();
                case Pricemethod.Max: return Max();
                case Pricemethod.Min: return Min();
            }

        }
    }

}

i want to avoid the switch statement and make it generic.

For a specific Pricemethod call a specific Calculation and return it.

get { return CalculatedPrice(Pricemethod); }

Wich pattern is to use here and maybe someone have a good implementation idea. Searched already for state pattern, but i dont think this is the right one.


Solution

  • how do I handle enums without using switch or if statements in C#?

    You don't. enums are just a pleasant syntax for writing const int.

    Consider this pattern:

    public abstract class PriceMethod
    {
      // Prevent inheritance from outside.
      private PriceMethod() {}
    
      public abstract decimal Invoke(IEnumerable<decimal> sequence);
    
      public static PriceMethod Max = new MaxMethod();
    
      private sealed class MaxMethod : PriceMethod
      {
        public override decimal Invoke(IEnumerable<decimal> sequence)
        {
          return sequence.Max();
        }
      }
    
      // etc, 
    }
    

    And now you can say

    public decimal Price
    {
        get { return PriceMethod.Invoke(this.PriceHistory); }
    }
    

    And the user can say

    myArticle.PriceMethod = PriceMethod.Max;
    decimal price = myArticle.Price;