Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

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

Posted by Paul on November 26, 2010


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

Scenario

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 = "Move";

 

if (command == "MoveUp")

    MoveUp();

else if (command == "MoveDown")

    MoveDown();

else if (command == "TurnLeft")

    TurnLeft();

else if (command == "TurnRight")

    TurnRight();

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

string command = "Move";

 

IDictionary<string, Action> actions = new Dictionary<string, Action>();

actions.Add("MoveUp", MoveUp);

actions.Add("MoveDown", MoveDown);

actions.Add("TurnLeft", TurnLeft);

actions.Add("TurnRight", TurnRight);

 

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 4 versions of Action.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s