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);
        }
    }
}

...

Delegates in C# and the reason for "Type Safe"

Delagates are known as type safe function pointers. Now now dont start to worry about what the hell is "type safe". Observer the following code snippet for a while. You'll realise the familiarity of the code.

What is a delegate?
delegate is a type safe function pointer. Using delegates you can pass methods as parameters. To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. This is why, delegates are called type safe function pointers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Deligates
{
    public delegate void DelegateFunction(string temp);
    class Program
    {
        public static void Main(string[] args)
        {
            DelegateFunction del = new DelegateFunction(functionOne);
            del("this is the delegate message");
        }

        public static void functionOne(string msg) 
        {
            Console.WriteLine(msg);
            Console.ReadLine(); // to hold the screen
        }
    }
}


To the costructor of the delegate, you pass the name of the function to, which you want to delegate teh point from.
            DelegateFunction del = new DelegateFunction(functionOne);

What/Why it is called 'type safe'?
The delegate checks for the return type in the function header. not only the parameter type which is passing in.

If the function header is like
            public static string functionOne(string msg) 
instead of
            public static void functionOne(string msg)

when delegate is defined as
            public delegate void DelegateFunction(string temp);
it will the return type of the signature and throws an error because it expects a void (non return). The signature of the delegate should match the signature of the function to which it points. If the signature of the method does not match, the compiler will throw an error. This is why the delegates are called as type safe function pointer, coz it depends on the type to act as a pointer in function.

Delegates gives the exposure of flexibility for the real time projects.