Lambda Expressions C# 3.0

Sun, February 18, 2007, 06:48 PM under dotNET | Orcas | LINQ
There are two aspects to lambda expressions and I will only discuss one of them in this post. The aspect not discussed is the one that is most useful, but to get there we must first understand the syntax, which follows.

Lambdas are simply shorthand to creating a delegate and pointing it to a method plus they offer type inference. Consider the following C# example:
delegate bool SomeDelegate(int i);
public void SomeMethod()
{
SomeDelegate sd = new SomeDelegate(OtherMethod);
//
// other code here
YetOneMore(sd);
}
private bool OtherMethod(int i)
{
return i > 2;
}
private void YetOneMore(SomeDelegate f)
{
bool res = f(5);
Console.WriteLine(res.ToString());
}
Nothing complicated (or useful) takes place. Before I rewrite it using a lambda expression, let's re-write it a bit using C# 2.0 anonymous methods:
delegate bool SomeDelegate(int i);
private void SomeMethod()
{
SomeDelegate sd =
delegate(int i){return i > 2;}
;
//
// other code here
YetOneMore(sd);
}
private void YetOneMore(SomeDelegate f)
{
bool res = f(5);
Console.WriteLine(b.ToString());
}
If you are not familiar with anonymous methods, basically we have inlined OtherMethod by using the delegate keyword.

Lambda expressions take this to the next level of conciseness.
This line:
    delegate(int i){return i > 2;}
can be written like this:
    (int i) => { return i > 2;}
so all we've done there is replace the delegate keyword with the funny syntax =>

However the beauty is that given the body only has a single return statement, we can make it even more concise *and* get the compiler to infer the parameter type:
 SomeDelegate sd = i => i > 2;
And that is the basics of lambdas: it looks weird, it is concise and it does some inference for us. In the future I will post about the other aspect of lambdas which is actually what most people are excited about: lambdas bound to parameter expressions.
Comments are closed.