Tuesday, September 18, 2012

Session Spotlight - Learn to Love Lambdas

I'll be speaking at SoCal Code Camp (Los Angeles) on October 13 & 14. If you're not signed up yet, head over to the website and let them know that you're coming: http://www.socalcodecamp.com/.

Back by popular demand: Learn to Love Lambdas

Lambda Expressions
Lambda expressions are a very powerful tool that can add elegance to our code.  The problem is that they look like a secret code the first time you see them.  You've probably come across something that looks like this:


It looks daunting, but it's fairly easy to learn.  The lambda expression that we have here is just an anonymous delegate.  If we were to use a more verbose syntax, we get something like this:


We are probably a bit more comfortable with this syntax.  Here, we can tell that we're hooking up some sort of event handler, and it has standard event handler arguments: object and some type of EventArgs.  Inside the method body, we are assigning the Result property of the EventArgs to display in a list box.

This anonymous delegate is equivalent to the lambda expression above.  To create the lambda expression, we just replace the "delegate" keyword (before the parameters) with the "goes to" operator (=>) after the parameters.  The parameter types are optional, so we can get rid of those.  Also, since the method body only has one statement, we can remove the curly braces.  This leaves us with a compact and readable syntax.

Delegates abound in the .NET framework (and in add-on frameworks like the Prism library).  Whenever we have LINQ extension methods, event handlers, callbacks, or tasks, we can use lambda expressions to add compact blocks of code right where they are most useful.  And in some instances (like when working with the Prism variants of RaisePropertyChanged) we can make our code more conducive to refactoring by replacing strings with compiler-checked pieces of code.

Once you get used to lambda expressions, they are extremely readable.  In this session, we'll learn the lambda syntax, use lambdas for asynchronous callbacks, see a really cool feature that makes code safer, and see how lambdas were designed to be used extensively in LINQ.  If you'd like to Learn to Love Lambdas, be sure to stop by my session at a code camp near you.

In addition to the SoCal Code Camp on Oct 13/14, I'll also be presenting this session at the Silicon Valley Code Camp on Oct 6/7 (this session is scheduled for 2:45 p.m. Sunday afternoon -- last session of the day).

Also be sure to check out the walkthrough and code samples here: Jeremy Bytes.

Hope to see you at an upcoming event.

Happy Coding!

No comments:

Post a Comment