Movatterモバイル変換


[0]ホーム

URL:


The MothMy Photo - click to enlarge

Developer, Former MVP, now at Microsoft - Best of2004,2005,2006,2007,2008,2009,2010,2011,2012,2013

« Extension methods C# 3.0 and VB9 | Lambda Expressions in VB9 »

Lambda Expressions C# 3.0

Sun, February 18, 2007, 06:48 PM underdotNET | 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 withanonymous methods, basically we have inlinedOtherMethodby using thedelegatekeyword.

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 singlereturnstatement, 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 [0] |#Permalink

© Copyright 2004-2025, Daniel Moth -Disclaimer
Powered by newtelligence dasBlog 2.3.9074.18820
Page rendered Friday, 18 July 2025 15:40:00 (Pacific Daylight Time, UTC-07:00)


About
Tags
Latest Posts
Archives

[8]ページ先頭

©2009-2025 Movatter.jp