Introduction
A number of articles are available on the web related to Anonymous methods and Lambda expression features. It is very confusing for the developers to decide when and where to use these features. I have tried to explain the concept in very simple manner.
Anonymous Methods
Anonymous method is a beautiful feature introduced in C# 2.0.
Anonymous methods are self explanatory that says "No Name” meaning anonymous methods let you declare a method body without giving it a name. Simply anonymous method has only body without name, optional parameters and return type.
Anonymous methods can only be created when using delegates. It acts as normal methods behind the scene 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 to be pointing to a function.
Let’s have an example to explain this.
Here, we have a customers
class having empID
, EmpName
and Salary
properties defined.
Below, we are trying to use find method which basically accepts a predicate of employee as parameter. Predicate is nothing but a predefined delegate which returns bool
.
So the code below has anonymous method which has delegate and it is returning 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();
}
}
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 method 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
Lambda concept has been introduced in C# version 3.0.
Lambda expression is an inline delegate which provides a way to represent anonymous methods. Anonymous methods and Lambda expression 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
Left side of the lambda operator "=>" represents the arguments to the method
Right side is the method body having 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);
}
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 the above anonymous method:
customers custDisply= lstCust.Find(delegate(customers cust)
{
return cust.EmpID==3;
});
We can see delegate
keyword and type of parameter provided for anonymous method.
Using Lambda, the same code can be rewritten as:
customers cusLambda = lstCust.Find(emp => emp.EmpID == 3);
So basically, we need not use delegate
keyword explicitly and also need not specify 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
Statement lambda has a statement block on the right side of the lambda operator "=>
".
- Expression lambda
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
delegate
keyword explicitly and also need not specify 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 type.
- Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.
- Lambda expression can be broken down into parameters.
Summary
Anonymous methods and lambda expression provide a way to use inline way of code. They will reduce the lines of code and are useful in places where a method is being used only once and the method definitions are short. It saves you the effort of declaring and writing a separate method to the containing class.