09 March 2015

Elegant way to SWITCH & If Else





Switch Case is one of the most traditional way of having conditional break up performed. Here is the new way which directs, delegates and performs the action as needed.

Ideally I have seen developer opting for If Else statements, adding my source code were I need to set a check bit based on the parameter Range.



int mynumbercheck=1000;
//Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
            { 
             { x => x < 10 ,    () => //Do this!...  },  
             { x => x < 100 ,    () => //Do this!...  },
             { x => x < 1000 ,    () => //Do this!...  },
             { x => x < 10000 ,   () => //Do this!... } ,
             { x => x < 100000 ,  () => //Do this!... },
             { x => x < 1000000 ,  () => //Do this!... } 
            };
Now to call our conditional switch

   myswitch.First(sw => sw.Key(mynumbercheck)).Value();

Hope this Help you and reduces if else code block

Rate Now: