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

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)

Leave a Reply

Your email address will not be published. Required fields are marked *