Lambda Expressions

When I first stumbled upon lambda expression in code, I was a bit confused because of their unusual notation. What’s x = (x,y) => (x*y) supposed to mean?

After reading up on lamba expressions on MSDN, it turned out they were just syntactic sugar for anonymous delegates, which in turn are just convenient shortcuts to creating delegate methods (+ helper classes). So here’s a short tutorial that will guide you from knowing only simple method calls to using lambda expressions!

Simple Method Calls

A normal method call is easy to understand. You define a method with some parameters and then you can call it from another place as often as you want:

class Traditional {

  /// <summary>Main entry point for the application</summary>
  public static void Main() {
    test(123);
  }

  /// <summary>Simple method that prints a number</summary>
  /// <param name="number">Number that will be printed</param>
  private static void test(int number) {
    Console.WriteLine("The number is : " + number);
  }

}

No explanation necessary here. Let’s step up the game.

Explicit Delegates

What if you wanted to call a method to notify a receiver about something happening, but you do want to fix the function that will be called in order to keep your code reusable?

Wouldn’t it be convenient if you could assign methods to a variable just like you can assign 123 to your int variable?

Delegates are exactly that. Whereas int is a type for storing integral numbers, a delegate is a type for storing methods:

class ExplicitDelegate {

  /// <summary>Delegate for a method with one int parameter</summary>
  /// <param name="number">Number that will be passed to the method</param>
  public delegate void TestDelegate(int number);

  /// <summary>Main entry point for the application</summary>
  public static void Main() {
    TestDelegate t = test1;

    t(123);

    t = test2;

    t(123);
  }

  /// <summary>Simple method that prints a number</summary>
  /// <param name="number">Number that will be printed</param>
  private static void test1(int number) {
    Console.WriteLine("The number is : " + number);
  }

  /// <summary>Simple method that prints a number multiplied by two</summary>
  /// <param name="number">Number that will be printed</param>
  private static void test2(int number) {
    Console.WriteLine("The number times two is : " + number * 2);
  }

}

As you can see, we have a variable t which gets assigned the Test1() method. Then we call that method through the t variable. Next we assign another method to t and call that one.

Any method that is compatible (meaning it returns void and takes an int) can be assigned to a variable of type TestDelegate.

Anonymous Methods

In C# 2.0 (supported by .NET 2.0 / Visual Studio 2005 and later) this can be considerably shortened.

Whereas we declared the methods that we assigned to our delegate variable (Test1() and Test2()) separately in the previous example, from C# 2.0 on we can directly assign code to a delegate variable without turning it into a separate method:

class AnonymousDelegate {

  public delegate void TestDelegate(int number);

  /// <summary>Main entry point for the application</summary>
  public static void Main() {
    TestDelegate t = delegate(int number) {
      Console.WriteLine("The number is : " + number);
    };

    t(123);

    t = delegate(int number) {
      Console.WriteLine("The number times two is : " + number * 2);
    };

    t(123);
  }

}

As a consequence, the code assigned to the delegate variable has no assigned method name, making it an anonymous method.

Lamba Expressions

With C# 3.0, we can shorten anonymous delegates even more by reducing them to this:

class LambaExpression {

  public delegate void TestDelegate(int number);

  /// <summary>Main entry point for the application</summary>
  public static void Main() {
    TestDelegate t = (int number) => Console.WriteLine(number);

    t(123);

    t = number => Console.WriteLine("The number times two is : " + number * 2);

    t(123);
  }

}

Let’s see, a lambda expression consists of two sides, to the left of the => is a list of the parameters and to the right of the => is the code.

The type of the parameters can be automatically deduced from the delegate type. In the second assignment of the example above, number will automatically become an int because t is a delegate with an int argument.

Lambda Expressions 2

Lamba expressions have an implicit built-in return statement. So if we wanted to use delegates for some calculations or perhaps filtering of some data, we can use them like this:

class LambaExpression2 {

  /// <summary>Delegate for a mathematical operation</summary>
  /// <param name="a">First operand</param>
  /// <param name="b">Second operand</param>
  /// <returns>The result of the mathematical operation</returns>
  public delegate int MathDelegate(int a, int b);

  /// <summary>Main entry point for the application</summary>
  public static void Main() {
    MathDelegate calc = (a, b) => (a * b);

    Console.WriteLine(calc(2, 4));

    calc = (a, b) => (a + b);

    Console.WriteLine(calc(2, 4));

    calc = (a) => (a + a);

    Console.WriteLine(calc(2, 4));
  }

}

That’s all there is behind lambda expressions. You will discover that there are some pretty cool use cases for lambdas and some developers got very creative in their use, but that’s for you to find out :)

Leave a Reply

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

Please copy the string ciWSbg to the field below:

This site uses Akismet to reduce spam. Learn how your comment data is processed.