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:

   1: int[] m = new int[] { 0, 5, 10 };
   3: Console.WriteLine
   4: (
   5:     m.Where
   6:     (
   7:         delegate(int x) 
   8:         { 
   9:             return x > 4; 
  10:         }
  11:      ).Average()
  12:  );
  13: //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:

   1: int[] m = new int[]{0, 5, 10};
   3: Console.WriteLine
   4: (
   5:     m.Where(x => x > 4).Average()
   6: );
   7: //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.

Skip to main content