Anonymous Methods and Lambda Features in C#

Introduction

A number of articles are available in the web related to Anonymous methods and Lambda expression features. It is very confusing for developers to decide when and where to use these features. I have tried to explain the concept in a very simple manner.

Anonymous methods

Anonymous methods is a beautiful feature introduced in C# 2.0.

Anonymous methods are self-explanatory, implying "No Name" (anonymous) methods that let you declare a method body without giving it a name. Simply an anonymous method has only a body without a name, optional parameters and a return type.

Anonymous methods can only be created when using delegates. It acts as normal methods behind the scenes but there is no way to explicitly call them in your code.

Sample C# syntax

Delegate void TestDel(int n);
...
TestDel nc = delegate (int x)
{
    Console.WriteLine("Anonymous Method: {0}", x);
};

Delegates are known to be function pointers, meaning they point to a function.

Let's have an example to explain this.

Here we have a customers class having an empID,EmpName and Salary properties defined.

In the following we are trying to use the find method that basically accepts a predicate of an employee as the parameter. Predicate is nothing but a pre-defined delegate that returns bool.

find method

So the code below has an anonymous method that has a delegate and it is returning a bool true matching empID 3.
 

customers custDisply= lstCust.Find(delegate(customers cust)
{

    return cust.EmpID==3;

});

Sample Code

public class Program

{

        public class customers

        {

            public int EmpID { get; set; }

            public string EmpName { get; set; }

            public float salary { get; set; }

        }

        static void Main(string[] args)

        {

            List<customers> lstCust = new List<customers>

            {

                new customers{EmpID=1,EmpName="Abhishek",salary=10000},

                new customers{EmpID=2,EmpName="David",salary=20000},

                new customers{EmpID=3,EmpName="Suman",salary=40000}

            };

           customers custDisply= lstCust.Find(

           delegate(customers cust)

           {

               return cust.EmpID==3;

          });

        Console.WriteLine("{0},{1},{2}",custDisply.EmpID,custDisply.EmpName,custDisply.salary); 

            Console.ReadLine();           

    }

}

An Anonymous method in event handling:

Button btnDisplay = new Button();

btnDisplay.Text = "Click";

btnDisplay.Click +=

delegate(object sender, EventArgs e)

{

   MessageBox.Show("Hello Every Body....");

};
Controls.Add(btnDisplay);

Important Sticky

  • A variable declared outside the anonymous method can be accessed inside the anonymous method.
  • A variable declared inside the anonymous method can't be accessed outside the anonymous method.
  • We use anonymous methods in event handling.
  • An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
  • An anonymous method can't access the ref or out parameters of an outer scope.

Lambda Expressions

The Lambda concept has been introduced in C# version 3.0.

A Lambda expression is an inline delegate that provides a way to represent anonymous methods. Anonymous methods and Lambda expressions are very similar.

It is used to create delegates or expression tree types and after compilation lambda expressions are converted into anonymous methods.

Lambda Syntax

(Parameters) => expression-or-statement-block

=> Lambda Operator

The left side of the lambda operator "=>" represents the arguments to the method.

The right side is the method body having an expression or statement block.

Let me explain the method call by an example.

Below we can see:

Delegate int delDisplay(int i);
static
void Main(string[] args)
{
    delDisplay del = x => x * x;

    int j = del (5);

 }

// result j = 25

Using Lambda Expression

using System.Linq.Expressions;
namespace MyLambda
{

    class Program

    {

        static void Main(string[] args)

        {

            Expression<del> myET = x => x * x;

        }

    }

}

When we see the example from above anonymous method as in the following:

anonymous method

We can see the delegate keyword and type of parameter provided for the anonymous method.

Using Lambda the same code can be re-written as:
customers cusLambda = lstCust.Find(emp => emp.EmpID == 3);

So basically we need not use the delegate keyword explicitly and also need not specify the type of input parameter. Lambda expressions are simpler to use than anonymous methods.

Sample Code

class Program

{

    public class customers

    {

        public int EmpID { get; set; }

        public string EmpName { get; set; }

        public float salary { get; set; }

    }

    static void Main(string[] args)

    {

        List<customers> lstCust = new List<customers>

        {

            new customers{EmpID=1,EmpName="Abhishek",salary=10000},

            new customers{EmpID=2,EmpName="David",salary=20000},

            new customers{EmpID=3,EmpName="Akash",salary=40000}

        };

       customers cusLambda = lstCust.Find(emp => emp.EmpID == 3);

       int count = lstCust.Count(X => X.EmpName.StartsWith("A"));

       Console.WriteLine("Count :" + count);

       Console.WriteLine("{0},{1},{2}", cusLambda.EmpID, cusLambda.EmpName, cusLambda.salary);

       Console.ReadLine();           

    }

}

Lambda expression types

  • statement lambda

    A Statement lambda has a statement block on the right side of the lambda operator "=>".
     
  • Expression lambda

    An Expression lambda has only an expression (no return statement or curly braces) on the right side of the lambda operator "=>".

Important Sticky

  • We need not use the delegate keyword explicitly and also need not specify a type of input parameter with lambda expressions.
  • A lambda expression cannot be assigned to an implicitly typed local variable since the lambda expressions do not have a type
  • Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.
  • A lambda expression can be broken down into parameters.

Summary

Anonymous methods and lambda expressions provide a way to use inline code. They will reduce the lines of code and are useful in places where a method is being used only once and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class.