DELEGATE VS ANONYMOUS FUNCTIONS VS LAMBDA EXPRESSIONS in C#


Hi  ALL ,

               In  C# 2.0 ,the only way to declare a delegate was  Named Method .

              Instantiate a delegate using named method  and  method is passed as a parameter .
 
                delegate   void del1(int x);

     void  dowork(int a)
    {
            

    }
                        

Del1  d=obj.
 
               

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions.

NAMED METHOD
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter, for example:
// Declare a delegate: delegate void Del(int x);

// Define a named method: void DoWork(int k) { /* ... */ }

// Instantiate the delegate using the method as a parameter:
Del d = obj.DoWork;


The above  is called using a named method


An anonymouse Funcion   is a Inline Statement   Or   Expression that can be used Wherever a delegate type is Expected .
There are two kinds of anonymous functions,

         Lambda Expressions (C# Programming Guide).

A   Lambda Expression is an Anonymous function that can be used to create delegates  OR Expression tree types .

By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.


  • Anonymous Methods  Explanation :
  • By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method. 

    BELOW is Example :

    // Create a delegate instance delegate void Del(int x);
    
    // Instantiate the delegate using an anonymous method
    Del d = delegate(int k) { /* ... */ };
    


     



    Comments