Lambdas in C#

You’ve been programming C# for a while. You know asynchronous programming, sockets, file IO, and even how to control remote computers. But you’ve gotten fed up. Every time you want to do something, you have to write a new private void foo() { // Code... } block. And you’re fed up with it. Luckily for you, there is a solution.

Enter the world of lambda expressions. MSDN defines a lambda as follows:

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

###Lambda Syntax### A lambda is assigned using the => operator, rather than a simple =. A lambda body can be either a code expression, such as:

 // x => x + 3
 x + 3

or a series of code statements wrapped in brackets. Multiple arguments are enclosed in parentheses:

Func<int, int, int> Add = (x, y) =>
{
	return x + y;
};

###Lambdas as Inline Functions###

A lambda expression, as said above, can be used to treat a method like a normal variable. Take, for example, this mathematical function:

f(x) = x + 3

This program traditionally evaluates f(x) for x = 1337:

using System;

namespace LambdasAreCool
{
    public class Program
    {
        public void Main()
        {
            var x = 1337;
            Console.WriteLine("f({0}) = {1}.", x, f(x));
        }

        public int f(int x)
        {
            return x + 3;
        }
    }
}

With a lambda expression, however, you don’t need to declare public void f(int x). We can rewrite our Main method like this:

public void Main()
{
	var foo = 1337;
	Func<int, int> f = x => x + 3;
	Console.WriteLine("f({0}) = {1}.", foo, f(foo));
}

Or even:

public void Main()
{
	var foo = 1337;
	Console.WriteLine("f({0}) = {1}.", foo, new Func<int, int>(x => x + 3)(foo));
}

###Lambdas as Method Arguments###

Lambdas can also be passed as arguments to methods. Take this program for example:

using System;

namespace LambdasAreCool
{
    public class Program
    {
        public void Main()
        {
            var foo = 1337;
            Console.WriteLine("f({0} = {1}", foo, Evaluate(x => x + 3, foo));
        }

        /// <summary>
        /// Evaluates a given function, f, for a given integral value, x.
        /// </summary>
        /// <param name="f">A method or delegate that accepts a single integer and returns an integer.</param>
        /// <param name="x">A 32-bit integer for which to evaluate f.</param>
        /// <returns>Returns the value of f(n) where n = x.</returns>
        public int Evaluate(Func<int, int> f, int x)
        {
            return f(x);
        }
    }
}

What are we doing? You’ll see that we actually use lambdas twice.

Our Evaluate function accepts a function as a parameter. As you can imagine, the argument f is expected to be a lambda. The documentation for f calls for “A method or delegate that accepts a single integer and returns an integer.” This requirement is fulfilled by the Func<int, int> type. According to MSDN, a Func<T, TResult>:

Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

Perfect. That’s just what we need. The Evaluate method simply has to call f(x). No extra code required. It’s that simple - such is the magic of lambdas.

The second place we use it is in the Main method.

Evaluate(x => x + 3, foo)

You can see here that we pass f(x) = x + 3 as our first argument. The second is the x restraint, x = 1337. C# evaluates this statement as 1340, which is the addition of 3 to 1337.

###In Conclusion###

Lambda expressions are a powerful language feature that enable you to take your programming to the skies. Master them, and you’ll be doing things you never imagined before. Thanks for reading.