May 4 2008

How lambda expressions can replace anonymous methods

Category: C#fossmo @ 23:45

In this blog post I will introduced the syntax of a lambda expression and how it can replace anonymous methods. I will not go into what expression trees are, though it has some very cool features.

So what is a lambda expression?
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

Lambda expression comes from the world of the lambda calculus:
In mathematical logic and computer science, lambda calculus, is a formal system designed to investigate function definition, function application and recursion. (source: Wikipedia)

A lambda operator is used in a lambda expression.
It is written like "=>" and is read as "goes to". It should not be confused with comparison operators such as <= and >=.
The left side of the lambda operator specifies the input parameter and the right side holds the expression of statement block.

Lambda expressions was introduced to the .NET community in .NET 3.5.

Two different lambda expressions
There are two kinds of lambda expressions. A lambda expression with an expression on the right side is called an expression lambda.
The second kind is a statement lambda, which looks similar to an expression lambda except that its right part consists of any number of statements enclosed in curly braces. 

Expression lambda
Expression lambda can be written as follows:

x => x + 1

It is read as "x goes to x plus 1".

Statement lambda
A statement lambda resembles an expression lambda except that the statement is enclosed in braces.

() => { statement };

Example code using statement lambda:

    class Program
    {
        delegate void WriteText();
        static void Main(string[] args)
        {
            WriteText wt = () => { Console.WriteLine("Text inside a statement lambda!"); };
            wt.Invoke();
            Console.ReadKey();
        }
    }


It is also possible to include multiple statements inside a statement block.

Many functional programming languages such as Lisp use lambda notations to define functions. In addition to allowing the expression of LINQ queries,
the introduction of lambda expressions into C# and VB.NET can be seen as a step toward functional languages.

Following are code examples of how you can use lambda expressions:

"The old way"
What this snippet does, is to output the first number bigger than three. It uses a named method called "FindNumberBiggerThanThree" to sort the numbers.

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(FindNumberBiggerThanThree);
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
        static bool FindNumberBiggerThanThree(int x)
        {
            return x > 3;
        }
    }


Using Anonymous methods

.NET 2.0 introduced a new construct; anonymous methods.
Instead of declaring a named method in your class and then referencing the method by name you can do this by creating a delegate:

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(delegate(int x) { return x > 3; });
            Console.WriteLine(result.ToString());
            Console.ReadKey();    
        }
    }


The advantage of using anonymous methods, over named methods, is that you can reference local variables in the "outer" method from within the anonymous method.
You don't have to clutter up your class with private methods that are only used once in order to pass some custom code to a method.

Using lambda expressions
The previous example with anonymous methods, is easy to read and understand, but it can be done better:

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(x => x > 3);
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
    }


In this example lambda expression is used. Compared to the example using the delegate keyword, lambda expressions simplifies the code a bit.

When to use lambda expressions
Whenever you need to pass some custom code to a method, lambda expressions are very useful.
The easy and readable syntax of lambda expressions also encourages the use of them.

I was introduced to lambda expressions thru mock-you (Moq is cool!) mocking framework and LINQ. I really like the syntax, and call on others to take a better look at what Lambda can do for them.

Tags:

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Comments are closed