Lambda Expressions

Lambda expressions simplify the syntax of anonymous methods. For example, the program below used an anonymous method that will be assigned to a delegate.

using System;
 
namespace AnonymousMethod
{
    public delegate void MessageDelegate(string message);
 
    public class Program
    {
        public static void Main()
        {
            MessageDelegate ShowMessage = new MessageDelegate(
            delegate(string message)
            {
                Console.WriteLine(message);
            }
            );
 
            ShowMessage("Hello World!");
        }
    }
}

By using lambda expressions, we can simplify the code like this:

using System;

namespace LambdaExpressionsDemo
{
    public delegate void MessageDelegate(string message);

    public class Program
    {
        public static void Main()
        {
            MessageDelegate ShowMessage = (message) => Console.WriteLine(message);

            ShowMessage("Hello World!");
        }
    }
}

Example 1 – Using a Lambda Expression

First, we indicate the parameter(s) without any type, then we use the => operator. We then write the statement(s) to be executed. The type of the parameter will automatically be detected by the compiler. Of course, the lambda expression must still match the signature of the delegate.

There are many forms of lambda expressions. For example, the first lambda expression we introduced in   Example 1 only has a single statement to execute. This is called an expression lambda.

If your delegate for your lambda expression has no parameters, then all you need to do is don’t provide any parameters in the lambda expression.

MessageDelegate ShowMessage = () => Console.WriteLine("Hello");

Note that you can also indicate the type of the parameters in a lambda expression.

MessageDelegate ShowMessage = (string message) => Console.WriteLine(message);

If you indicate the type of one parameter, then the other parameters should also have their type. For example, you cannot do the following.

MessageDelegate ShowMessage = (string message1, message2) =>
 Console.WriteLine(message1);

If your lambda expression needs multiple statements, then you simply put braces. When a lambda expression has braces, it is called a statement lambda.

MessageDelegate ShowMessage = (message) =>
{
        Console.WriteLine(message);
        Console.WriteLine("Some more message");
}

The following is an example of a lambda expression which returns a value.

SampleDelegate GetSquare = (number) => { return number * number; };

Note that when using the return statement, you should always use statement lambdas by enclosing the statement in curly braces. If a lambda expression should only contain a single return statement, then you can simplify the above code even more by transforming it to its expression lambda version.

SampleDelegate GetSquare = (number) => (number * number);

Note the use of parentheses to make the return expression more clearer. If a lambda expression has a single parameter and return statement, then you can simplify it even more by removing the parentheses.

SampleDelegate GetSquare = number => number * number;

But if a lambda expression has 2 or more parameters, then you must enclose the parameters in parentheses.

SampleDelegate GetSum = (num1, num2) => num1 + num2;

The above lambda expression has two parameters and returns the sum of the values of that two parameters.

Lambda Expression Example

Using lambda expressions, it is now easier to pass anonymous methods as arguments to other methods. Consider the example below.

using System;

namespace LambdaExpressionsDemo2
{
    public delegate int Arithmetic(int x, int y);

    public class Program
    {
        public static int GetResult(Arithmetic Operation, int num1, int num2)
        {
            return Operation(num1, num2);
        }

        public static void Main()
        {
            Console.Write("Enter first number: ");
            int num1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter second number: ");
            int num2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Sum = " + GetResult((x, y) => x + y, num1, num2));
            Console.WriteLine("Difference = " + GetResult((x, y) => x - y, num1, num2));
            Console.WriteLine("Product = " + GetResult((x, y) => x * y, num1, num2));
            Console.WriteLine("Quotient = " + GetResult((x, y) => x / y, num1, num2));
        }
    }
}

Example 2 – Lambda Expressions in Action

Enter first number: 5
Enter second number: 2
Sum = 7
Difference = 3
Product = 10
Quotient = 2

We created a delegate (line 5) that accepts two integer arguments and returns an integer value. We then use this delegate as a parameter for the GetResult method (lines 9-12). The other two parameters are the two numbers that will be involved in different operations as we will see. Since the first parameter is a delegate, the argument must be a reference to a method, an anonymous method, or a lambda expression. Using a lambda expression makes the code more readable and requires less typing. Lines 21-24 invokes the GetResult() method. Notice that each call has a lambda expression as its first argument. The only difference is the operation that every lambda expression will do on the two values. If we use anonymous methods instead, then our code would be longer and harder to read.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *