CodeHappy

January 12, 2008

Introducing Lambdas in C#

Filed under: General Programming — pwrighta @ 10:06 pm
Tags:

C# 3.0 introduces “Lambdas” and in so doing catches C# up to the raft of scripted languages (Python, Ruby etc) that have supported them for quite some time. But, just what are they?

Technically Lambda is the 11th letter of the Greek alphabet, and over the years has become synonymous with a programming construct in languages such as Python and Lisp called closures. If you’ve never come across Lambdas and closures before (and most of your average C# developers haven’t) the names can be quite intimidating. In reality, it’s all really quite simple.

In most simple C# code, functions A and B will interact only when one calls the other. Function A gets its own local variables and calls Function B. Function B gets its own local variables too, and is unable to access the variables defined in Function A, unless of course they are passed as parameters.

C# 2.0 gave us anonymous functions, allowing programmers to define Function B right inside Function A. A closure is formed when we do this giving Function B access to the local variables of A. One of the benefits of an anonymous function, other than saving typing, is that it allows us to assign a function to a delegate variable or parameter on the fly.

For example, if you want to search a List collection in .NET, you’d typically define a predicate function, a function with the same parameters as a .NET Predicate, and then hand it to the Find method. This code, for example, implements a property called Position that lets an item in a list find its own position in a collection.

        public int Position
        {
            get
            {
                if (this.HasParent)
                {
                    return _parent.Children.FindIndex(FindChild);
                }
                else { return 0; }
            }
        }

        private bool FindChild(Item i)
        {
            return i == this;
        }

Find iterates through the items in the list, and passes each one to the predicate function, FindChild. In .NET 1.0 you’d define the function just like any other, and then assign the function to a delegate variable, and then pass the delegate variable into the Find method. In .NET 2.0 you could just define the delegate inline.

        public int Position
        {
            get
            {
                if (this.HasParent)
                {
                    return _parent.Children.FindIndex(delegate(Item i) { return i == this; });
                }
                else { return 0; }
            }
        }

Much nicer isn’t it. Lambdas simply make this even easier. Here’s the same code using a Lambda in C# 3.0.

        public int Position
        {
            get
            {
                if (this.HasParent)
                {
                    return _parent.Children.FindIndex(i => i == this);
                }
                else { return 0; }
            }
        }

In the previous example, to define the anonymous method we have to use the delegate keyword, and then declare the parameters and types to pass into our method, then actually wrap the code to the method in braces.

In the example above though all that overhead goes away and we use the ‘goes to’ symbol (=>) to specify a lambda. It looks a little alien the first time you see it, but you’ll soon get accustomed to it. => is read as goes to, so in the above example the code says i is a parameter that goes to the expression i == this, a comparison obviously, returning a simple true or false.

Notice how types are not specified here at all. The C# 3.0 compiler infers the type. At compile time it can easily guess the types to use from the values in the expression (‘this’ has a type obviously, and FindIndex uses a delegate that specifies types in its definition as well).

Technically what I’m using here is called an Expression Lambda. It’s simply an anonymous method wrapping a simple expression the value of which is returned (a Boolean in this case). It’s also possible to specify a Statement lambda, an anonymous method containing a bunch of code inside the usual brace block delimiters.

For example, the Expression Lambda above could be converted into a Statement Lambda, with the same results, like this

       public int Position
        {
            get
            {
                if (this.HasParent)
                {
                    return _parent.Children.FindIndex(i => { return i == this; } );
                }
                else { return 0; }
            }
        }

There’s a little more overhead with this and it looks a lot more like a C# 2.0 anonymous method now. The upside is that you can add some considerable functionality into a Lambda Statement, a lot more in fact than you could get away with in a simple Lambda Expression.

Lambdas are more than just a convenience mechanism in C# 3.0 code though, and play an integral part in building LINQ expressions, which I’ll no doubt cover in a few blogs sometime in the future.

2 Comments »

  1. Didn’t know C# could do that! Very cool. Although, why have two different “types” of lambdas? Statement vs Expression? Why not just have 1 that works in both situations? Less confusion.

    Comment by Eric — January 13, 2008 @ 1:18 pm | Reply

  2. Hey, I noticed that your article about lambda expressions is linking to mine: http://dpatrickcaldwell.wordpress.com/2008/07/28/writing-anonymous-methods-with-lambda-expressions/. I’m going to have to keep an eye on your blog. Great information.

    Comment by dpatrickcaldwell — September 11, 2008 @ 1:54 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.