Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Switch statement alternative

0.00/5 (No votes)
22 Jul 2014 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here