Joe White’s Blog

Life, .NET, and Cats


TechEd 2008 notes: Understanding C# Lambda Expressions

This was a lunch session, so pretty short. It turned out to be pretty introductory-level, just about grokking the syntax (which I pretty much already did).

Understanding C# Lambda Expressions
Scott Cate
myKB.com

Operators: most are very mnemonic, very self-explanatory. But what about =>?

Read => as “reads into” or “feeds into”.

BuildMatrix((a, b) => (a+b).ToString());

History of Delegates in .NET

  • Forget the compiler for a minute. What does the word “delegate” mean? “I don’t have time to (or don’t know how to) do this; I’m going to offload it to someone else and take the credit.”
  • You’ve mastered delegates if you could write a class with an event, and wire up that event, in Notepad, without Intellisense.
  • Define the delegate type. No implementation, just a signature.
  • .NET 1.0: Pass the method name as a parameter (or whatever). (Actually, in 1.0 I think maybe you had to do new DelegateType(MethodName).)
  • .NET 2.0: anonymous delegates. BuildMatrix(delegate(int a, int b) { return (a+b).ToString(); }
    • Return type is inferred.
  • .NET 3.0: BuildMatrix((a, b) => (a+b).ToString());
    • The stuff after => is an anonymous delegate. The stuff before it is the parameter list.
    • You can define the parameter types, or the compiler can infer them.
    • Can omit parentheses if there’s only one parameter.
  • Same thing without predefining the delegate type: void BuildMatrix(Func<int, int, string> operate)
  • Don’t need curly braces and don’t need return — can just put an expression. You can also put braces with statements (in which case you do need return).

Errata — details the presenter got mixed up:

  • Built a grid in HTML, and it looks like he got his X and Y loops reversed. Yes, this is nitpicky.
  • Told us you can make two delegates with the same name but different parameters (one with two ints and one with two decimals). You can’t; it won’t compile (I double-checked). They can have the same name if they have a different number of generic parameters (since the number of generic parameters is part of the name), but you can’t do it if they’re non-generic.
  • Told us the compiler generates a new delegate type behind the scenes when you pass an anonymous delegate (it doesn’t, it uses the actual delegate type that the function expects; I double-checked)

There are no responses to “TechEd 2008 notes: Understanding C# Lambda Expressions” yet.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Joe White's Blog copyright © 2004-2011. Portions of the site layout use Yahoo! YUI Reset, Fonts, and Grids.
Proudly powered by WordPress. Entries (RSS) and Comments (RSS). Privacy policy