Click here to Skip to main content
15,115,667 members
Articles / Programming Languages / C#
Tip/Trick
Posted 17 Jul 2014

Tagged as

Stats

44.4K views
10 bookmarked

Switch statement alternative

Rate me:
Please Sign up or sign in to vote.
2.93/5 (11 votes)
22 Jul 2014CPOL
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nitin S
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
SuggestionThe switch guys are missing the point Pin
jimibt27-May-15 22:15
Memberjimibt27-May-15 22:15 
Nice little concise article (and no disrespect to the commentators supporting simple switc/if's). Although in general, switch and if statements are great for simple linear codeflow, your example demonstrates something that would require logic loops if not using Func<> and Action. Consider the following:

C#
class Programm
   {
       // define a few methods - all Actions
       // would be defined as methods - 2 for now
       static void DefaultMethod()
       {
           Console.WriteLine("Default case");
       }
       static void LessThan300Method()
       {
           Console.WriteLine("Smaller than 300");
       }

       static void Main()
       {
           Func<int, bool> Default = (x => true);

           var cases = new Dictionary<Func<int, bool>, Action>
           {
               { x => x < 3 ,    () => Console.WriteLine("Smaller than 3")   } ,
               { x => x < 30 ,   () => Console.WriteLine("Smaller than 30")  } ,
               { x => x < 300 ,  () => LessThan300Method()},
               { Default,        () => DefaultMethod()}
           };

           // in a real scenario, the workflow steps would vary per object
           int[] fauxWorkflowSteps = {285, 301, 29, 1};

           foreach (var fauxWorkflowStep in fauxWorkflowSteps)
           {
               cases.First(kvp => kvp.Key(fauxWorkflowStep)).Value();
           }

           Console.ReadKey();
       }
   }


In the above scenario the simple changes to the base myNum var requires no code branches to represent its output - everything is simply deferred in memory and can be recalled simply by invoking the dictionary with the appropriate key. Imagine this as a simple workflow where the key was a step and each of the actions was a separate method with a parameter for a base class. You then get a feel for why this technique shines over switch statements.

Tomas Ruksenas (http://www.codeproject.com/Messages/4886933/Another-valid-case.aspx[^]) alluded to a similar usecase with his code addition regards parameters changing etc..

However, I do agree horses for courses

Thanks for the article...

modified 28-May-15 4:04am.

SuggestionAnother valid case Pin
Tomas Ruksenas20-Aug-14 22:31
MemberTomas Ruksenas20-Aug-14 22:31 
GeneralMy vote of 1 Pin
ahagel23-Jul-14 19:06
professionalahagel23-Jul-14 19:06 
GeneralRe: My vote of 1 Pin
John B Oliver24-Jul-14 13:07
MemberJohn B Oliver24-Jul-14 13:07 
GeneralRe: My vote of 1 Pin
ahagel24-Jul-14 14:32
professionalahagel24-Jul-14 14:32 
QuestionWhat about letting the compiler do its magic on switch statements? Pin
Frederico Barbosa22-Jul-14 23:51
MemberFrederico Barbosa22-Jul-14 23:51 
AnswerRe: What about letting the compiler do its magic on switch statements? Pin
Nitin S23-Jul-14 3:54
professionalNitin S23-Jul-14 3:54 
GeneralRe: What about letting the compiler do its magic on switch statements? Pin
Frederico Barbosa29-Jul-14 2:49
MemberFrederico Barbosa29-Jul-14 2:49 
QuestionCan't Linq be used here? Pin
George Swan22-Jul-14 22:02
MemberGeorge Swan22-Jul-14 22:02 
AnswerRe: Can't Linq be used here? Pin
Nitin S23-Jul-14 3:55
professionalNitin S23-Jul-14 3:55 
GeneralMy vote of 1 Pin
Dan Colasanti21-Jul-14 12:41
professionalDan Colasanti21-Jul-14 12:41 
GeneralRe: My vote of 1 Pin
Nitin S23-Jul-14 3:57
professionalNitin S23-Jul-14 3:57 
GeneralRe: My vote of 1 Pin
FatCatProgrammer23-Jul-14 6:53
MemberFatCatProgrammer23-Jul-14 6:53 
GeneralRe: My vote of 1 Pin
Dan Colasanti23-Jul-14 8:22
professionalDan Colasanti23-Jul-14 8:22 
GeneralRe: My vote of 1 Pin
John B Oliver24-Jul-14 13:23
MemberJohn B Oliver24-Jul-14 13:23 
GeneralRe: My vote of 1 Pin
Dan Colasanti24-Jul-14 17:05
professionalDan Colasanti24-Jul-14 17:05 
Questionquestion Pin
Simon_Whale21-Jul-14 4:41
professionalSimon_Whale21-Jul-14 4:41 
QuestionWouldn't this be an if ... else rather than a switch? Pin
PeejayAdams21-Jul-14 4:33
MemberPeejayAdams21-Jul-14 4:33 
QuestionA List is better in this case. Pin
Paulo Zemek18-Jul-14 5:52
mvaPaulo Zemek18-Jul-14 5:52 
AnswerRe: A List is better in this case. Pin
helcode21-Jul-14 2:24
Memberhelcode21-Jul-14 2:24 
GeneralRe: A List is better in this case. Pin
leppie21-Jul-14 2:31
Memberleppie21-Jul-14 2:31 
AnswerRe: A List is better in this case. Pin
James Curran21-Jul-14 3:09
MemberJames Curran21-Jul-14 3:09 
QuestionYou need a default case Pin
James Curran18-Jul-14 5:29
MemberJames Curran18-Jul-14 5:29 
AnswerRe: You need a default case Pin
Nitin S20-Jul-14 20:42
professionalNitin S20-Jul-14 20:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.