how do i handle Enums without using switch or if statements in C#?
For Example
enum Pricemethod
{
Max,
Min,
Average
}
... a
You could create an interface
, and class
es that implement it:
public interface IPriceMethod
{
double Calculate(IList<double> priceHistorie);
}
public class AveragePrice : IPriceMethod
{
public double Calculate(IList<double> priceHistorie)
{
return priceHistorie.Average();
}
}
// other classes
public class Article
{
private List<Double> _pricehistorie;
public List<Double> Pricehistorie
{
get { return _pricehistorie; }
set { _pricehistorie = value; }
}
public IPriceMethod Pricemethod { get; set; }
public double Price
{
get {
return Pricemethod.Calculate(Pricehistorie);
}
}
}
Edit: another way is using a Dictionary
to map Func
s, so you don't have to create classes just for this (this code is based on code by Servy, who since deleted his answer):
public class Article
{
private static readonly Dictionary<Pricemethod, Func<IEnumerable<double>, double>>
priceMethods = new Dictionary<Pricemethod, Func<IEnumerable<double>, double>>
{
{Pricemethod.Max,ph => ph.Max()},
{Pricemethod.Min,ph => ph.Min()},
{Pricemethod.Average,ph => ph.Average()},
};
public Pricemethod Pricemethod { get; set; }
public List<Double> Pricehistory { get; set; }
public double Price
{
get
{
return priceMethods[Pricemethod](Pricehistory);
}
}
}
how do I handle enums without using
switch
orif
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;