.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Sohaib Khalid

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

How to map a command to method without using if/switch?

Posted By:Jean Paul       Posted Date: November 26, 2010    Points: 50    Category: ASP.NET    URL: http://www.dotnetspark.com  

Here I am trying to show the advantage of using Lambda expressions along with some built in delegates.


The user will input a command like "MoveUp", "MoveDown", "TurnLeft", "TurnDown".  Based on the commands, you have to call the the methods MoveUp(), MoveDown(), TurnLeft(), TurnDown() respectively.

The old code will look like:

string command = "MoveUp";

if (command == "MoveUp")

else if (command == "MoveDown")

else if (command == "TurnLeft")

else if (command == "TurnRight")

We can replace the same code with Lambda and built-in delegate Action as:

string command = "MoveUp"; 

IDictionary actions = new Dictionary();

actions.Add("MoveUp", MoveUp);
actions.Add("MoveDown", MoveDown);
actions.Add("TurnLeft", TurnLeft);
actions.Add("TurnRight", TurnRight);

// Execute
actions.Where(a => a.Key == command).FirstOrDefault().Value();

Note: The Action is a built-in delegate with void as return and no arguments input.  There are total of 5 versions of Action.

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend