65.9K
CodeProject is changing. Read more.
Home

Switch statement alternative

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.93/5 (11 votes)

Jul 18, 2014

CPOL
viewsIcon

59140

switch statement alternative using anonymous code

Background

Switch statement alternative using Func type

Using the code

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


class Programm
{
    static void Main()
    {
        Func<int, bool> Default = (x=> true);
        
        var myNum = 1200;
        var cases = new Dictionary<Func<int, bool>, 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.

 

 

Thanks for the comments @John B. Oliver