CSharp - Compare the usage of Anonymous method and Lambda expression

Description

Compare the usage of Anonymous method and Lambda expression

Demo

using System;
public delegate int Mydel(int x, int y);

class Program//from   w ww .  ja v  a 2s.co m
{
    public static int Sum(int a, int b) { return a + b; }

    static void Main(string[] args)
    {
        Console.WriteLine("*** Exploring Lambda Expression***");
        //Without using delgates or lambda expression
        int a = 25, b = 37;
        Console.WriteLine("\n Calling Sum method without using a delegate:");
        Console.WriteLine("Sum of a and b is : {0}", Sum(a, b));

        //Using Delegate( Initialization with a named method)
        Mydel del = new Mydel(Sum);
        Console.WriteLine("\n Using delegate now:");
        Console.WriteLine("Calling Sum method with the use of a delegate:");
        Console.WriteLine("Sum of a and b is: {0}", del(a, b));

        //Using Anonymous method(C# 2.0 onwards)
        Mydel del2 = delegate (int x, int y) { return x + y; };
        Console.WriteLine("\n Using Anonymous method now:");
        Console.WriteLine("Calling Sum method with the use of an anonymous method:");
        Console.WriteLine("Sum of a and b is: {0}", del2(a, b));

        //Using Lambda expression(C# 3.0 onwards)
        Console.WriteLine("\n Using Lambda Expresson now:");
        Mydel sumOfTwoIntegers = (x1, y1) => x1 + y1;
        Console.WriteLine("Sum of a and b is: {0}", sumOfTwoIntegers(a, b));
    }
}

Result

A lambda expression is an anonymous method or unnamed methods of a delegate instance.

Suppose we have the following delegate:

public delegate int Mydel(int x, int y);

And we have assigned and invoked a lambda expression as

(x1, y1) => x1 + y1

You can see that each parameter of the lambda expression corresponds to delegate parameters (x1 to x, y1 to y).

The type of the expression (x+y is an int) corresponds to return the type of the delegate.

Lambda operator => is used in lambda expressions.

We can omit parentheses if our lambda expression has only one parameter; for example, we can write something like this to calculate the square of a number:

x=>x*x

Related Topic