Posted by: Cirilo Meggiolaro | 11/8/2008

Tip of the day #25 – Lambda expressions

Yesterday’s tip described anonymous methods and how to execute delegates without named functions.

Let’s talk now about lambda expressions (new feature from .NET framework 3.0) that are basically anonymous methods with a new syntax that may indeed make the code shorter.

Lambda expressions have the following format:

left side => right side

On the left side the parameters will be defined (if necessary) while the right side is the implementation itself. The right associative operator => separates the left side parameters from the right side statements.

Important: When more than one parameter is necessary, they should be enclosed by parenthesis.

A simple example

The following example creates a delegate for a function that evaluates if a number is positive or negative using lambda expression to implement the function body.

delegate bool IsPositive(decimal number);

IsPositive myDel = number => number > 0;
bool result1 = myDel(123); //True
bool result2 = myDel(-123); //False

Generic functions with query operators

Lambda expressions also provide a way to create functions with query operators. The following example uses the generic delegate Func<input, result>:

Func<decimal, bool> myFunc = number => number > 0;
bool result1 = myFunc(123); //True
bool result2 = myFunc(-123); //False

The calculator example

The following example uses the same delegate from Tip of the day #24 – Anonymous Methods.

delegate void Calculate(decimal x, decimal y, MyOperationEnum operation);

public enum MyOperationEnum

The implementation of the calculate method with lambda expression will be:

Calculate calc = (decimal x, decimal y, MyOperationEnum operation) =>
switch (operation)
case MyOperationEnum.Add:
Console.WriteLine(“Result (Add): {0}”, x + y);
case MyOperationEnum.Subtract:
Console.WriteLine(“Result (Subtract): {0}”, x – y);
case MyOperationEnum.Divide:
Console.WriteLine(“Result (Divide): {0}”, x / y);
case MyOperationEnum.Multiply:
Console.WriteLine(“Result (Multiply): {0}”, x * y);

calc(123, 321, MyOperationEnum.Add);
calc(125, 321, MyOperationEnum.Subtract);
calc(125, 321, MyOperationEnum.Multiply);
calc(125, 321, MyOperationEnum.Divide);

To get more details about lambda expressions, click here!


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s


%d bloggers like this: