The Case of Switch-Case in C#

By Anoop Madhusudanan

Vote on HN

A quick rant on using switch-cases in C#. In Javascript, most developers prefer creating a lean object that can be re-used, instead of a stubborn switch case. For example, instead of this Switch Case implementation,

switch (foo) {
	case 'case1':
		alert('case1 code');
		break;
	case 'case2':
		alert('case2 code');
		break;
	default:
		alert('hm, default code');
		break;
}
a number of developers may consider this one as more elegant - because it is re-usable and more testable.
var mySwitch= {
'case1' : function() {
	alert('case1 code');
},
'case2' : function() {
	alert('case2 code');
},
'default' : function() {
	alert('default code');
}
};


if (mySwitch[foo]) {
	mySwitch[foo]();
} else {
	mySwitch['default']();
}
I was thinking about implementing something along similiar lines in C#, to re-factor few fat switch cases using a Dictionary. Obviously, this is context specific - one approach won't fit all the scenarios. Here is a quick example to clarify the point.

    public class SwitchCase : Dictionary<string,Action>
    {
        public void Eval(string key)
        {
            if (this.ContainsKey(key))
              this[key]();
            else
             this["default"](); 
        }
    }


    //Now, somewhere else

            var mySwitch = new SwitchCase
            {
                { "case1",  ()=>Console.WriteLine("Case1 is executed") },
                { "case2",  ()=>Console.WriteLine("Case2 is executed") },
                { "case3",  ()=>Console.WriteLine("Case3 is executed") },
                { "case4",  ()=>Console.WriteLine("Case4 is executed") },
                { "default",()=>Console.WriteLine("Default is executed") },
            };

            mySwitch.Eval(c);
This provides loose coupling, and you can even modify the logic for each case easily using a setter or so. Happy Coding!!
© 2012. All Rights Reserved. Amazedsaint.com