Dec 31, 2013

C# Switch statement alternative

You can use a Dictionary to create a mapping of Condition => Action.

class Programm
{
    static void Main()
    {
        Func Default = (x=> true);
        
        var myNum = 1200;
        var cases = new Dictionary, Action>
        {
            { x => x < 3 ,    () => Console.WriteLine("Smaler than 3")   } ,
            { x => x < 30 ,   () => Console.WriteLine("Smaler than 30")  } ,
            { x => x < 300 ,  () => Console.WriteLine("Smaler than 300") },
            { Default,        () => Console.WriteLine("Default case") }
        };
        
        cases.First(kvp => kvp.Key(myNum)).Value();
    }
}
 

This technique is not a general alternative to switch statement.
Suppose you have a workflow system that is required to perform validation of a data item. Different validation routines are executed based upon some state of the data being processed. Using this technique means
a) You do not have a switch statement with over 100 case statements - very difficult to read.
b) You do not have to include conditional logic in the case statement for each validation routine - very difficult to maintain.
c) You can offload the validation routines and conditional logic into a database where the customer can then update when a validation routine executes as per their requirements - very flexible.