Saturday, 23 June 2012

Concepts of Anonymous Method,Lambda Expression,func, actions,Predicates and Expression Trees


Anonymous  methods in C#.net  :

Anonymous methods is a new language feature in C# 2.0, Anonymous methods allow us to define a code block where a delegate object is acceptable. This facility saves us an extra step of creating a delegate for small code blocks that we want to pass to a delegate. It also removes the cluttering of small methods in the class code. Let us say, for instance, that we have a string collection class named MyCollection. This class has a method that retrieves all the items in the collection that satisfies a user supplied criteria, i.e., the caller decides whether a particular item in the collection qualifies for being retrieved as part of the return array from this method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace AnonymousMethodsandDelegates
{
    class Program
    {
        delegate int PointToAddFunction(int num1, int num2);
        static void Main(string[] args)
        {
            Stopwatch objwatch = new Stopwatch();

            for (int m = 0;m < 10; m++)
            {
                objwatch.Reset();
                objwatch.Start();
                for (int l = 0; l < 1000; l++)
                {
                    //another Method
                    PointToAddFunction p = delegate(int x, int y)
                   {
                       return x + y;
                   };
                    int z = p.Invoke(23, 45);
                  
                }
                objwatch.Stop();
                Console.WriteLine(objwatch.ElapsedTicks.ToString());
            }
            Console.ReadLine();
        }
        static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
    }
}





Output is :  Recording For Anony Methods(Elapsing Time)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace AnonymousMethodsandDelegates
{
    class Program
    {
        delegate int PointToAddFunction(int num1, int num2);
        static void Main(string[] args)
        {
            Stopwatch objwatch = new Stopwatch();       
            for (int m = 0;m < 10; m++)
            {
                objwatch.Reset();
                objwatch.Start();
                for (int l = 0; l < 1000; l++)
                {
                    //another Method
                    PointToAddFunction p = Add;
                    int z = p.Invoke(23, 45);
                  
                }
                objwatch.Stop();
                Console.WriteLine(objwatch.ElapsedTicks.ToString());
            }
            Console.ReadLine();
        }
        static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
    }
}
Recording for Named Delegates(Elapsing Time) : 


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

namespace ConsoleLambda
{
    class Program
    {
        delegate double CalArePointer(int r);
       static   CalArePointer cpointer = CalculateArea;
        static void Main(string[] args)
        {
            double area = cpointer.Invoke(23);
            Console.WriteLine("Area of the Circle is : " + area);
            Console.ReadLine();
        }
        static double CalculateArea(int r)
        {
            return 3.14 * r * r;
        }
    }
   
}

  -------------------------xxxxxx Or  xxxx----------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleLambda
{
    class Program
    {
        delegate double CalArePointer(int r);
     
        static void Main(string[] args)
        {
            CalArePointer cpointer = new CalArePointer(delegate(int r)
                   {
                       return 3.14 * r * r;
                   }
           );
            double area = cpointer(20);
            Console.WriteLine("Area of the Circle is : " + area);
            Console.ReadLine();
        }
      
    }
   
}

By using Lambda Expressions :

CalArePointer cpointer = r => 3.14 * r * r;           
            double area = cpointer(20);
            Console.WriteLine("Area of the Circle is : " + area);

Using Lambda Expressions+Functions :

Func<double, double> cpointer = r => 3.14 * r * r;
            double area = cpointer(20);
            Console.WriteLine("Area of the Circle is : " + area);

Using Action:

Action<string> Myaction = y => Console.WriteLine(y);
            Myaction("Welcome");

Using Predicates :

Predicate<string> checkgreaterthan5 = x => x.Length > 5;
            List<string> ostring = new List<string>();
            ostring.Add("Mohan");
            ostring.Add("Venkat");
            string str = ostring.Find(checkgreaterthan5);
            Console.WriteLine(str);

Expression Trees :

   Coding for  (23+56)-(40+20)

BinaryExpression b1 = Expression.MakeBinary(ExpressionType.Add,
                                                      Expression.Constant(23), Expression.Constant(56));
            BinaryExpression b2 = Expression.MakeBinary(ExpressionType.Add,
                                       Expression.Constant(40), Expression.Constant(20));
            BinaryExpression b3 = Expression.MakeBinary(ExpressionType.Subtract, b1, b2);

          int result=  Expression.Lambda<Func<int>>(b3).Compile()();
          Console.WriteLine("Result is : " + result);


No comments:

Post a Comment