Tuesday, May 25, 2010

Lambda Expression in C# .Net

Lambda expression is a new way to defines an anonymous function. That function can take arguments (if any) & can return a value from the function.

“=>” (read as ‘goes to’) is the operator to define the lambda expression. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.

Consider the following e.g.

class Program

    {

        /// <summary>

        /// Declare a delegate

        /// </summary>

        /// <param name="i">Input parameter</param>

        /// <returns>Result</returns>

        delegate int myDelegate(int i);

 

        public static int Square(int i)

        {

            return i * i;

        }

 

        public static void Main()

        {

            int input = 11;

            myDelegate del = Square;

            int result = del(input);

 

            Console.WriteLine("Result : " + result);

            Console.ReadLine();

        }

    }

Here I defined a delegate & a function to calculate the ‘Square’ of the input number. I can rewrite the same code using lambda expression which is as follows

    class Program

    {

        /// <summary>

        /// Declare a delegate

        /// </summary>

        /// <param name="i">Input parameter</param>

        /// <returns>Result</returns>

        delegate int myDelegate(int i);

 

        public static void Main()

        {

            myDelegate del = myInput => myInput * myInput;

            int result = del(input);

 

            int input = 11;

            Console.WriteLine("Result : " + result);

            Console.ReadLine();

        }

    }

 

Basically myInput => myInput * myInput; expression defines an anonymous method which takes ‘myInput’ as input, does multiplication & returns the output (int).

 

 

  • We can have multiple input parameters in an lambda expression

(x, y) => x * y

  • We can explicitly declare the variable type in the input parameters. if no data type is given then compiler would infer its type.

(int x, int y) => x * y

  • Use empty parentheses if there are no arguments to be passed to the method.

() => MyMethod()

  • Use { } if your function has multiple statements

myInput =>

            {

                myInput = myInput + 10;

                myInput = myInput + 20;

            };

 

We can use standard Func<> delegate with lambda expression. The same code can be written as

class Program

    {

        public static void Main()

        {

 

            Func<int, int> del = i => i * i;

            int result = del(10);

            Console.WriteLine("Result : " + result);

 

            Console.ReadLine();

        }

    }

Lambda expression is mainly meant for using it LINQ.

No comments: