Monday, March 25, 2013

C#: Lambda expressions , Action , Func and Predicate

What is a delegate?


A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

  1. The name of the method on which it make calls.
  2. Any argument (if any) of this method.
  3. The return value (if any) of this method


Where are Delegates used?

The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place. 

This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.



Defining a Delegate in C#
when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking one integers and returning an double.


Example:
namespace MyPoc
{
   public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea
            //that points to MyClass.CalculateArea().
            CalArea del1 = new CalArea(MyClass.CalculateArea);
            //Invoke CalculateArea() method using the delegate.
            double result = del1(5);
            Console.WriteLine("Result= {0}\n", result);
//Other way of calling deligate
            //CalArea del2=MyClass.CalculateArea;
            // double result1= del2.Invoke(5);
        }     

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

Anonymous methods

Anonymous methods let you declare a method body without giving it a name. Behind the scenes, they exist as 'normal' methods; however, there is no way to explicitly call them in your code. Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword.

namespace MyPoc
{
   public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea with inline Anonymous Method implementation for CalculateArea
               CalArea del1 = new CalArea(
                delegate(int r)
                {
                    return 3.14 * r * r;
                }

                );
            //Invoke deligate
            double result = del1(5);           
            Console.WriteLine("Result= {0}\n", result);
        }

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

    }

}

What is Lamda Expression?

Lambda expression is another powerful syntactic sugar making C# functional. In this post, “Lambda expression” simply means “C# Lambda expression”. The native concept of lambda expression will be introduced in the later lambda calculus posts.
According to MSDN:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.
It is just simple functional expression, which looks like number => number > 0. The left side of => is the function parameters, and the right side is the function body.

 public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea with inline Anonymous Method implementation for CalculateArea
            //   CalArea del1 = new CalArea(
            //    delegate(int r)
            //    {
            //        return 3.14 * r * r;
            //    }

            //    );
            ////Invoke deligate using lamda expresssion           
            CalArea del = r => 3.14 * r * r;
            double result = del(5); 
            Console.WriteLine("Result= {0}\n", result);
        }
       }


These are quick definitions of the three classes that are covered in the article:
  • Predicate - delegate that takes parameter(s), runs code using the parameter(s) and always returns a Boolean
  • Func - delegate that takes parameter(s), runs code using the parameter(s) and returns the type that you specify
  • Action - delegate that takes parameter(s), runs code using the parameter(s) and doesn’t return anything


 public class Program
    {
     
        static void Main(string[] args)
        {
            //Lamda expresssion and Func(has input and has output)        
            Func<int,double> del = r => 3.14 * r * r;
            double result = del(5);
            Console.WriteLine("Result= {0}\n", result);

            //Lamda expresssion and Action(has input and has void output/no outout)        
            Action<string> MyAction = r => Console.WriteLine(string.Format("Hello, this is my text :{0}", r));
            MyAction("Vijay");

            //Lamda expresssion and Predicates(has input and return bool) //mostly useed for search and to check if return type is true or false
            Predicate<string> MyPredicate = r => r.Length > 5;
           Console.WriteLine( MyPredicate("VijayMishra"));
          

//use of above in real time
  List<string> myString = new List<string>();
           myString.Add("Vijay");
           myString.Add("VijayMishra");
           string str = myString.Find(MyPredicate);
           Console.WriteLine(str);
        }
       }

No comments:

Post a Comment