November 18, 2010

C# Lambda Expressions

For quite a while now I have been wondering about lambda expressions. I've started seeing more and more of them in code examples, and there has obviously been a lot of talk about them. But most of the examples I've seen have not been very intuitive. I finally decided to see what they we're all about, and was surprised about how simple they are to understand. They are not really anything new, just a new shorthand for doing things that C# could already do.

I started my journey be reading chapter 11 of Pro C# 2010 and the .NET 4 Platform (As a side note I've read a number of the other chapters, and it looks like a decent book so far.) I thought it was interesting that lambda expressions we're grouped in the same chapter as delegates and events, but after reading the chapter, it all makes sense now. This is probably oversimplifying it, but lambda expressions are just "syntactic sugar" for creating anonymous functions, and working with delegates. They allow a developer to easily write a basic inline function for event handlers or anywhere else a delegate is needed.

The basic format for lambda expressions is arguments => statement. The expressions can have 0 or more arguments and 1or more statements. The most common case I've seen is probably one argument and one statement, and the nice thing about a single statement is that the result of the statement is the "return" value of the expression. One of the other great things about lambda expressions is that in most cases the parameters can be implicitly typed, so that can mean a few less characters to type, and simpler, easier to understand expressions.

I still don't know how often I will use them, but it is nice to know how simple they are and how easily I can define event handlers now. What would have taken a significant amount of boiler plate code and definitions and a function, can now be done in a single, quick line of code.

No comments: