Lambda Expressions

With the release of C# 3.0 and Visual Basic 9, both languages added support for lambda expressions. Lambda expressions form the basis of lambda calculus which (this will seem a bit mathy) is a formal system which is used to explore mathematical and programmatic topics such as recursion and computability.  Lambda calculus plays a crucial role in language theory and formed the foundation for functional programing concepts and type systems.

In MUCH simpler terms a lambda expression is a concise and easy to write anonymous function.  Infact C# and VB they are merely syntactic sugar for anonymous delegates.  The inspiration for adding them was to simply make passing functions around less cumbersome.  For example:

int[] m = new int[] { 0, 5, 10 };

Console.WriteLine
(
    m.Where
    (
        delegate(int x)
        {
            return x > 4;
        }
     ).Average()
 );
//Outputs: 7.5

This snippet takes an array of integers, filters it to only values greater than 4, and then takes its average.  We pass in an anonymous delegate to the Where clause to define how we want to filter the array.  While this works great and is readable it is needlessly verbose.  With the addition of lambda expression that code becomes:

int[] m = new int[]{0, 5, 10};

Console.WriteLine
(
    m.Where(x => x > 4).Average()
);
//Outputs: 7.5

Now I can hear everyone screaming “SO WHAT!”.  And I will admit it isn’t a huge change, but it is cleaner and easier to read.