Monday, October 7, 2013

Lamda Expressions - C#

Lamda expressions are used when needed to make a delegate code more simple. Not only in delegates, but also in anonymous methods. Or else to build an expression tree.

Lamda expression is an anonymous function, whcih contains expression and a statement.

Lamda Operator : "=>" read as goes to.
left side of the lamda operator specifies the input parameter.

Default Delegate Snippet :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExpression
{
    class Program
    {
        delegate double DelegatePointerFunc(int r);
        static DelegatePointerFunc cpointer = CalculateArea;

        static void Main(string[] args)
        {
            double area = cpointer.Invoke(20);
        }

        static double CalculateArea(int r)
        {
            return 3.14 * r * r;
        }
    }


Anonymous Method : used to get rid of the extra Calculate Area Function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExpression
{
    class Program
    { ///Introducing Anonymous Method
      
        delegate double DelegatePointerFunc(int r);
        //static DelegatePointerFunc cpointer = CalculateArea;

        static void Main(string[] args)
        {
            //double area = cpointer.Invoke(20);
            DelegatePointerFunc cpointer = new DelegatePointerFunc(
                delegate(int r)
                    {
                        return 3.14 * r * r;
                    }
                );
            double Area = cpointer(20);
        }

       // static double CalculateArea(int r)
       //  {
       //     return 3.14 * r * r;
       // }
    }
}

Lamda Expression  Code Snippet :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExpression
{
    class Program
    { 
        delegate double DelegatePointerFunc(int r);
        //static DelegatePointerFunc cpointer = CalculateArea;

        static void Main(string[] args)
        {
            //DelegatePointerFunc cpointer = new DelegatePointerFunc(
            //    delegate(int r)
            //        {
            //            return 3.14 * r * r;
            //        }
            //    );
            //double Area = cpointer(20);

            // USING LAMBDA EXPRESSIONS 
            DelegatePointerFunc cpointer = r => 3.14 * r * r;
            double Area = cpointer(20);
        }
    }
}

...

No comments:

Post a Comment