Lambda Expressions and Delegates

One of the great new .NET 3.5 features is Lambda Expressions. You’ve probably seen Lambda expressions with LINQ in generic collections (I know I write a lot of these), like so:

IList contacts = new List();
// Populate contacts from a DB or other source
IList inactiveContacts = contacts.Where(c => c.Active == false);

The code contacts.Where(c => c.Active == false) is precisely a lambda expression. Lambda expressions come from lambda calculus and closures, but that’s not the main point of this article.

What’s interesting to note is that under the hood, that lambda expression is really equivalent to a delegate. LINQ is a bit complicated, so let’s go with a simpler example.

Microsoft’s Lambda Expressions page gives a simplistic example; say you have a delegate for any function that tests a string and does some sort of sate-checks. You might have a delegate like this:

delegate bool TestString(string s);
TestString currentTestMethod;

Then, go on to define a test method — perhaps one to check for a non-empty length. You could write code like this:

bool CheckIfEmpty(string s) {
return s != string.Empty;
currentTestMethod = CheckIfEmpty;

What’s interesting is that, you can write functionally equivalent code like so:

delegate bool TestString(string s);
TestString currentTestMethod = (s => s != string.Empty);

In some programming languages, they call this “anonymous functions.” You have really defined the same function as CheckIfEmpty above–but it’s done inline, and with a lambda expression.

Under the hood, this really creates an anonymous method and assigns it; but using lambda expressions, not only are your functions anonymous (and thus, don’t pollute your classes), but it’s syntactically cleaner and easier to tell when you read the code, what exactly is going on. No need to check delegate signatures and jump up and down your .cs files.

And that’s a brief, whirlwind tour of lambda expressions and delegates. You can read much, much more detail on Microsoft’s Lambda Expressions article.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms and tagged , , . Bookmark the permalink.

Leave a Reply

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