Blog - Title

Lambda Expressions

Lambda Expressions

  • Comments 67

[Blog Map]  [Table of Contents]  [Next Topic]

Note: This article is a topic in a much larger tutorial on writing pure functional code in C#.  Lambda expressions are only one of the pieces in a much larger puzzle.  Functional programming in C# allows us to write shorter programs that perform better, and are much more robust.  Query Composition using Functional Programming Techniques explains lambda expressions in their proper context.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC
In order to learn functional programming and a more declarative style of writing code, we need first to cover some basic material.  One of the first concepts is that of lambda expressions.  Lambda expressions can be summarized in one sentence:

Lambda expressions are simply functions/methods.

They have a different syntax, primarily so that they can be written in expression context (more on this shortly) instead of as a member of a class.  However, that is all they are.  For instance, the following lambda expression:

c => c + 1

is a function that takes one argument, c, and returns the value c + 1.

Actually, they are slightly more complicated than this, but not much more.  For the purposes of this tutorial, you only use lambda expressions when calling a method that takes a delegate as a parameter.  Instead of writing a method, creating a delegate from the method, and passing the delegate to the method as a parameter, you can simply write a lambda expression in-line as a parameter to the method.

To show lambda expressions in context, consider the problem where you have an array with 10 digits in it, and you want to filter for all digits greater than 5.  In this case, you can use the Where extension method, passing a lambda expression as an argument to the Where method:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
 
foreach (int i in source.Where(x => x > 5))
    Console.WriteLine(i);

To understand the semantics of this code, you needn't find some method elsewhere in the source code that does the selection; the code that you need to read is much tighter and smaller.  It reflects your intent in a much cleaner fashion.

Later on in this tutorial, you'll see a number of uses of the standard query operators.  Many of the standard query operators, including Where, take delegates as an argument, so this means that we can call them passing a lambda as an argument.

First, a quick review of delegates:

Defining, Creating, and Using a Delegate

In C#, a delegate is a data structure that refers to either a static method, or an object and an instance method of its class.  When you initialize a delegate, you initialize it with either a static method, or a class instance and an instance method.

The following code shows the definition of a delegate and a method that can be used to initialize the delegate:

// Defines a delegate that takes an int and returns an int
public delegate int ChangeInt(int x);
 
// Define a method to which the delegate can point
static public int DoubleIt(int x)
{
    return x * 2;
}

Now, you can create and initialize an instance of the delegate, and then call it:

ChangeInt myDelegate = new ChangeInt(DelegateSample.DoubleIt);
Console.WriteLine("{0}", myDelegate(5));

This, as you would expect, writes 10 to the console.

Using an Anonymous Method

With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place:

ChangeInt myDelegate = new ChangeInt(
    delegate(int x)
    {
        return x * 2;
    }
);
Console.WriteLine("{0}", myDelegate(5));

Using a Lambda Expression

With Lambda expressions, the syntax gets even terser:

ChangeInt myDelegate = x => x * 2;
Console.WriteLine("{0}", myDelegate(5));

This lambda expression is an anonymous method that takes one argument x, and returns x * 2.  In this case, the type of x and the type that the lambda returns are inferred from the type of the delegate to which the lambda is assigned.

If you wanted to, you could have specified the type of the argument, as follows:

ChangeInt myDelegate = (int x) => x * 2;
Console.WriteLine("{0}", myDelegate(5));

Using a Lambda with Two Arguments

When using the Standard Query Operators, on occasion, you need to write a lambda expression that takes two arguments.

If you have a delegate that takes two arguments:

// Defines a delegate that takes two ints and returns an int
public delegate int MultiplyInts(int arg, int arg2);

You can declare and initialize a delegate:

MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));

Statement Lambda Expressions

You can write a more complicated lambda expression using statements, enclosing the statements in braces.  If you use this syntax, you must use the return statement, unless the lambda returns void:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
 
foreach (int i in source.Where(
        x =>
        {
            if (x <= 3)
                return true;
            else if (x >= 7)
                return true;
            return false;
        }
    ))
    Console.WriteLine(i);

Sometimes developers wonder how to pronounce the => token.

If the lambda expression is a predicate, expressing some condition: c => c.State == "WA" then the => can be spoken as "such that".  In this example, you could say "c such that c dot state equals Washington".  If the lambda expression is a projection, returning a new type: c => new XElement("CustomerID", c.CustomerID); then the => can be spoken as "becomes".  In the above example, you could say "c becomes new XElement with a name of CustomerID and its value is c dot CustomerID".  Or "maps to", or "evaluate to", as suggested in the comments below.  But most often, I just say "arrow".  J

A quick note: predicates are simply boolean expressions that are passed to some method that will use the boolean expression to filter something.  A lambda expression used for projection takes one type, and returns a different type.  More on both of these concepts later.

Lambda Expressions that Return Void

A lambda expression that returns void is not very useful in the context of functional programming because the only possible reason for such a function is that it has side-effects, and is not pure (more on this later in the tutorial), but it is part of C# 3.0 syntax, so I'll cover it here.  Sometimes developers will use a void statement lambda expression for writing an event handler.  This has the benefit that the syntax is terser, and the program is smaller.  In addition, the lambda expression can refer to local variables in the enclosing scope.  This is part of C#'s implementation of closures.  The only way to write a lambda expression that returns void is to write a statement lambda expression.  The following example shows defining a void delegate, declaring an instance of it, and calling it.

// Defines a delegate that takes a string and returns void
public delegate void OutputToConsole(string arg);
 
static void Main(string[] args)
{
    OutputToConsole o = a => {
        Console.WriteLine(a);
    };
    o("Hello, World");
}

If you write a lambda expression for a delegate that returns void and takes no arguments, it results in interesting syntax:

// Defines a delegate that takes no arguments and returns void
public delegate void OutputHelloToConsole();
 
static void Main(string[] args)
{
    OutputHelloToConsole o = () =>
    {
        Console.WriteLine("Hello, World");
    };
    o();
}

The Func Delegate Types

The framework defines a number of parameterized delegate types:

public delegate TR Func<TR>();
public delegate TR Func<T0, TR>(T0 a0);
public delegate TR Func<T0, T1, TR>(T0 a0, T1 a1);
public delegate TR Func<T0, T1, T2, TR>(T0 a0, T1 a1, T2 a2);
public delegate TR Func<T0, T1, T2, T3, TR>(T0 a0, T1 a1, T2 a2, T3 a3);

In the above delegate types, notice that if there is only one type parameter, it is the return type of the delegate. If there are two type parameters, the first type parameter is the type of the one and only argument, and the second type is the return type of the delegate, and so on. Many of the standard query operators (which are just methods that you call) take as an argument a delegate of one of these types. These delegate definitions are useful to you when writing your own methods that take a delegate as an argument.

using System;
using System.Collections.Generic;
 
class Program
{
    static List<T> MyWhereMethod<T>(IEnumerable<T> source,
        Func<T, bool> predicate)
    {
        List<T> l = new List<T>();
        foreach (T item in source)
            if (predicate(item))
                l.Add(item);
        return l;
    }
 
    static void Main(string[] args)
    {
        int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
 
        List<int> filteredList = MyWhereMethod(source,
            i => i >= 5);
        foreach (int z in filteredList)
            Console.WriteLine(z);
    }
}

The Action Delegate Types

The framework defines a number of parameterized delegate types for delegates that return void:

public delegate void Action();
public delegate void Action<T0>(T0 a0);
public delegate void Action<T0, T1>(T0 a0, T1 a1);
public delegate void Action<T0, T1, T2>(T0 a0, T1 a1, T2 a2);
public delegate void Action<T0, T1, T2, T3>(T0 a0, T1 a1, T2 a2, T3 a3);

Sometimes API designers will include an event that takes one of these delegate types as an argument, and you can write a lambda expression for the argument.  As with the Func delegate types, these delegate definitions are useful to you when writing your own methods that take a delegate as an argument.  This uses the interesting syntax of () => { /* body of void function here */ };

using System;
using System.Collections.Generic;
using System.Threading;
 
class Program
{
    static void SomeAsynchronousMethod(Action complete)
    {
        // just pretending to be asynchronous in this example
        Thread.Sleep(1000);
        complete();
    }
 
    static void Main(string[] args)
    {
        SomeAsynchronousMethod(() => { Console.WriteLine("Done"); });
    }
}

Expression Trees

Lambda expressions can also be used as expression trees.  This is an interesting topic, but is not part of this discussion on writing pure functional transformations.

[Blog Map]  [Table of Contents]  [Next Topic]

Leave a Comment
  • Please add 1 and 7 and type the answer here:
  • Post
  • Time to continue with the longest running series on C# 3.0. Lambda expressions originated from lambda

  • You've been kicked (a good thing) - Trackback from DotNetKicks.com

  • One of the questions I've had about the new lambda expression syntax in C# 3.0 is how to pronounce it...

  • Really brief and nice. I like it ! And this article, of course ... :)

  • I think that the => operator should be pronounced as "induces", as it does in fommal logics.

  • Great article - feels like it's pitched right at me.

    You could pronounce "=>" as "returning" - it works in both your examples.

  • Body: I arrived a bit late in the morning and missed the opening Keynote on Silverlight by Jason Zander

  • Do you want to know what's new in the 3rd version of the lovely C# :) ? just check the links below:

    ...

  • it's a little difficult between telling the difference between this and a normal function call.  i think people would be better served if you passed the delegate into a quicksort function for pedagogical purposes.

  • Hello there

     I found this article by searching on google. What can I say, I made some tests regarding Lambda Expressions. One of them is that, for sure, the parameters are still STRONGLY TYPE. Just analyze that :

    public delegate T SomeDelegate<T> (T A,T B);

    and then :

    SomeDelegate<String> calcul = (x, y) =>

    {

      MessageBox.Show(x.GetType().ToString());

      return String.Empty;

    };

    So, the typeof(x) is String, just like the type value that was passed for the "SomeDelegate<T>".

    There are much more things interesting regarding Lambda Expressions. I used them most of all in custom Extention Methods.

  • Or... try that :

    MessageBox.Show(

               ((SomeDelegate<String>)((x, y) =>

               {

                       MessageBox.Show(x.GetType().ToString());

                   return (x + y);

               })).Invoke("2", "3").ToString()

               );

  • Reading Anders' post on Lexical Closures, Deferred Execution and Kicker Methods with respect to LINQ

  • I'm a little late to the dance; however, great explaination on the white-box use of lamda expressions.  Thank you... -Dan

  • An article, concise and to the point. "Keep it simple" is the way to go.

  • Other names I use for "=>" are "maps to" or "evaluates to". But ofcourse no answer is "right" ;-)

Page 1 of 5 (67 items) 12345