May 2008 - Posts - Virtual Static Void

Virtual Static Void

Keeping track of the ever changing...

May 2008 - Posts

Switching on Enums

Having read Jared Parsons blog entry on Switching on Types, I was inspired to follow on with a class that switches on enumerated values. This is achievable using a regular switch, but this approach seems more elegant.

The expected usage as follows:

  // given enumeration
public enum HoldingField
{
Holding,
BookValue,
MarketValue,
EffectiveExposure,
}

...

// code to extract result from respective property of "h"
decimal result = 0m;
EnumSwitch.Do
(
HoldingField,
EnumSwitch.Case(HoldingField.Holding, ()=> result = h.Holding),
EnumSwitch.Case(HoldingField.BookValue, ()=> result = h.BookValue),
EnumSwitch.Case(HoldingField.MarketValue, ()=> result = h.MarketValue),
EnumSwitch.Case(HoldingField.EffectiveExposure, ()=> result = h.EffectiveExposure)
);

Here is the code for the EnumSwitch class:

  public static class EnumSwitch
{
public class CaseInfo
{
public bool IsDefault { get; set; }
public Enum Target { get; set; }
public Action Action { get; set; } } public static void Do(Enum source, params CaseInfo[] cases) { foreach (var entry in cases) { if (entry.IsDefault || source == entry.Target) { entry.Action(source); break; } } } public static CaseInfo Case(Enum value, Action action) { return new CaseInfo() { Action = x => action(), Target = value }; } public static CaseInfo Default(Action action) { return new CaseInfo() { Action = x => action(), IsDefault = true }; } }