Lambda Expression in C#

Anonymous methods can be used in the place where there is a use of a delegate. Lambda Expression is extension of anonymous method. A lambda expression is an anonymous function that can contain expressions and statements. The term lambda expression comes from lambda calculus. In mathematics it is denoted as λ, where λ is the Greek letter lambda.

Lambda expressions provide same functionality, as anonymous methods can do. They are more readable and compact.

Lambda expressions use the lambda operator =>, which is read as "goes to".

Example:
The lambda expression x => x * x is read "x goes to x multiply by x."

The left side of the lambda operator indicates the input parameters and the right side shows the expression or statement block.

Example

using System;
namespace ConsoleApplication1
{    
    class Program
    {
        delegate int delDemo(int n);
        static void Main(string[] args)
        {
            delDemo delObj = y => y * y;
            Console.WriteLine("Enter a number");
            int x = Convert.ToInt32(Console.ReadLine());
            int j = delObj(x);
            Console.WriteLine("The squre of {0} is {1}",x,j);
            Console.ReadLine();
        }
    }
}

Statement Lambda

A statement lambda looks like an expression lambda, but the statement(s) should be enclosed in braces.

Syntax of statement lambda:

(Input parameters) => {statements}

Example

using System;
namespace ConsoleApplication1
{
    class Program
    {
        delegate int factDelegate(int n);
        static void Main(string[] args)
        {
            int fact = 1;
            factDelegate delObj = y => {            
                for (int i = 1; i <= y; i++)
                {
                    fact = fact * i;
                }
                return fact;
            };
            Console.WriteLine("Enter a number");
            int x = Convert.ToInt32(Console.ReadLine());
            int j = delObj(x);
            Console.WriteLine("The factorial of {0} is {1}", x, j);
            Console.ReadLine();
        }
    }
}

Func and Action built-in generic delegate

For using delegate we have to use following procedure

  • Declare a delegate.
  • Create methods with implementation. Methods prototype should be same as delegate.
  • Create instance of delegate and refer to method.
If you don’t want to create custom delegate, then you can use Func delegate type. C# 3.0 provides Func built-in generic delegate types, that is located in the System namespace.

public delegate TResult Func<in T, out TResult>(T arg)

Func delegate enables you to create a method that can be passed as a parameter without explicitly declaring a custom delegate. This delegate can refer to a method that takes up to 16 Parameters and returns a value. The last type parameter is used for the return type.

Signatures of the Func delegate types in .NET 3.5:

TResult Func<TResult>()
TResult Func<T,TResult>(T arg)
TResult Func<T1,T2,TResult>(T1 arg1, T2 arg2)
TResult Func<T1,T2,T3,TResult>(T1 arg1, T2 arg2, T3 arg3)
TResult Func<T1,T2,T3,T4,TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Example

using System;
namespace ConsoleApplication1
{
    class FuncDemo
    {
        //ShowWelcome() method does not take parameter and return string type.
        public string ShowWelcome()
        {
            return string.Format("Welcome at TutorialRide");
        }
        //Add method takes two parameter and return one integer type.
        public int Add(int a, int b)
        {
            return a + b;
        }
        //ShowInformation method takes two string parameter and return one string type.
        public string ShowInformation(string firstName, string lastName)
        {
            return string.Format("Your Name is {0} {1}", firstName, lastName);
        }
    }
    class Program
    {
       
        static void Main(string[] args)
        {
            FuncDemo obj = new FuncDemo();
            Func<string> welcomeObj = obj.ShowWelcome;
            Func<int, int, int> addObj = obj.Add;
            Func<string, string, string> showObj = obj.ShowInformation;
            Console.WriteLine("Enter the First Number");
            int a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the Second Number");
            int b = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the First Name");
            string firstName = Console.ReadLine();
            Console.WriteLine("Enter the Last Name");
            string lastName =Console.ReadLine();
            Console.WriteLine("\n**********************\n");
            Console.WriteLine(welcomeObj());
            Console.WriteLine("The addition of {0} and {1} is = {2}",a,b,addObj(a,b));
            Console.WriteLine(showObj(firstName,lastName));
            Console.WriteLine("\n**********************\n");
            Console.ReadLine();

        }
    }
}


Output:

Enter the First Number
10
Enter the Second Number
20
Enter the First Name
Raj
Enter the Last Name
Parihar

**************************************
Welcome at TutorialRide
The addition of 10 and 20 is = 30
Your Name is Raj Parihar
*************************************

Action delegate

The Action delegate provides the equivalent functionality as Func. It is used for a function that may or may not take parameters and does not return a value.

Func delegate works only for those methods, which has return type.