Friday, September 7, 2007

Lambda expressions introduction

NET 2.0 introduced Anonymous Methods. The idea behind anonymous methods it to write methods inline to the code. They are mainly used for small methods that don't require any need for reuse. For example, we have this code:

   1: bool isGreaterThan5(int n)
   2: {
   3:     return n > 5;
   4: }
   5:  
   6: ...
   7:  
   8: int GetGreatersThanFives(List<int> numbers)
   9: {
  10:     return numbers.Find(isGreaterThan5);
  11: }

We can code it with anonymous method:



   1: int GetGreaterThanFives(List<int> numbers)
   2: {
   3:   return numbers.Find(
   4:         delegate(int n) { return n > 5; }
   5:     );
   6: }

c# 3.0 represent cool thing: Lambda expressions.
Lambda Expressions make things easier by allowing you to avoid the anonymous method and that annoying statement block.

Instead



   1: delegate(int n){ return n > 5; }

We can write:



   1: n =>  n > 5

The form of Lambda expressions is:


argument-list => expression

Parameters to Lambda Expressions


The parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:



   1: (int x) => x + 100         // explicitly typed parameter
   2:  
   3: (x,y) => return x * y;    // implicitly typed parameter

Lambda Expressions with Multiple Parameters



   1: (x, y) =>  return x * y

Lambda Expressions without Parameters



   1: () => Console.WriteLine("Hello world!")      // No parameters

I think that's enough intro to Lambda Expressions.
I will follow up with a part 2 to show more about this cool fteature: Expression Trees, how LINQ uses it to pass code as parameters and more.

No comments: