Lambda Expressions
In C# 3.0, Microsoft has further extended the concept of anonymous methods, which were introduced in C# 2.0. To understand what a Lambda Expression is, you'll need to first understand anonymous methods.
Suppose you have just added a Button control to a Windows Form. In C# 1.0/1.1, you'd need to wire up the event handler for the control using the following statements:
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
}
Essentially, you added an event handler by using the
"+=" operator and then defined the event handler explicitly. In C# 2.0, you can rewrite the above statements using anonymous method, like this:
button1.Click += delegate
{
Console.WriteLine("Button clicked!");
};
Instead of defining the event handler explicitly, you embed the code in the event handler inside an anonymous method. Now, in C# 3.0, you can further shorten the anonymous method using a Lambda expression, like this:
private void Form1_Load(object sender, EventArgs e)
{
button1.Click +=
(_sender, _args)=> Console.WriteLine("Button clicked!") ;
}
Lambda expressions are compact functions that can be passed as arguments to another method. In the above example, the Lambda expression is:
(_sender, _args)=> Console.WriteLine("Button clicked!")
Lambda expressions have the following format:
params => expression(s)
Note that in this example, both
_sender and
_args are parameters of the Lambda expression (they've been prefixed with an underscore character to differentiate them from the variable used in the
Form1_Load event handler). It's not mandatory to define the type of parameter(s) you are passing into the Lambda expression; they are inferred automatically based on the context in which they are defined. Also, you can have multiple statements in the expression section of the lambda expression. Here's an example:
button1.Click += (object _sender,EventArgs _args) =>
{
Console.WriteLine("Button clicked!");
Console.WriteLine("Button clicked!");
};
More to Come!
Now that you've gotten a taste of the new features available in C# 3.0, you can understand how they help save you time and hassle. Stay tuned for Part 2 and find out how C#'s Language Integrated Query (LINQ) support does the same.