Translate

Monday, January 14, 2013

Introduction to lambda C# (Lambda expression tutorial))

What is a Lambda ?

Lambda expression can be thought of a shorthand way of writing a function to assign it to a delegate. (Lamda functions return delegates)

For example what is shown below

namespace Lambda
{
    internal class Program
    {
        public delegate int ProductDelegate(int a, int b);
        private static void Main(string[] args)
        {
            var test = new Test();
            ProductDelegate productDelegate = test.Multiplier;
            var product = productDelegate(2, 3);
        } 
    }

    public class Test
    {
        public int Multiplier(int a, int b)
        {
            return a * b;
        }
    }

}

can be replaced by

namespace Lambda
{
    internal class Program
    {
        public delegate int ProductDelegate(int a, int b);
        private static void Main(string[] args)
        {
            ProductDelegate productDelegate = (x,y)=>(x*y);//read as x y goes to x*y
            var product = productDelegate(2, 3);
        }
    }
}

The compiler infers the type of input parameters x,y and the return type of x*y from the definition of the delegate it is assigned to.


Here is another example that shows the syntax of anonymous methods and lambda expression one after another, for comparison

using System;

namespace Lambda
{
    class Program
    {

        delegate int AddDelegate(int a, int b);

        static void Main(string[] args)
        {
            AddDelegate addDelegate;

            addDelegate = Add;//Assign a method to the delegate
            Console.WriteLine(addDelegate(1,2));// Displays 3

            addDelegate = delegate(int a, int b) { return (a + b); };//Assign an anonymous method to a delegate
            Console.WriteLine(addDelegate(11, 9));// Displays 20

            addDelegate = (a, b) => (a + b);//Assign a lambda expression to a delegate
            Console.WriteLine(addDelegate(10, 5));// Displays 15

        }

        public static int Add(int a,int b)
        {
            return (a + b);
        }

    }

}


How to write multiline Lambda Functions ?


using System;
 
internal class Test
{
    public delegate void PrintArray(int[] arr);
 
    private static void Main()
    {
        int[] array = {1, 2, 3};
 
        PrintArray printArray = x =>
        {
            foreach (int i in x)
            {
                Console.WriteLine(i);
            }
        };
 
        printArray(array); //displays 1 2 3
    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator