Deep C# - Anonymous Methods, Lambdas And Closures
Written by Mike James   
Monday, 19 September 2016
Article Index
Deep C# - Anonymous Methods, Lambdas And Closures
From Anonymous Methods to Lamdas
Expressions Lambda to Expression Trees
Two Patterns for Closure


Standard delegates

Lambdas have made is much easier to use standard types of function within the .NET framework and to make it even easier there are a range of standard pre-defined delegate types.

The Action delegates provide a way to encapsulate a method that does something, i.e. is an "action", returning void and anything from zero to 16 parameters. For example:

Action<int> HelloInst = (param1) =>
  MessageBox.Show( Hello delegate World"
                    + param1.ToString());

To use Action with additional parameters you simply keep specifying them up to the maximum. For example:

            MyAction=(p1,p2,p3) => ...

The Func delegate works in the same way as the Action delegate but you can also specify a return type in addition to up to sixteen input parameters. The return type is specified as the final type. For example:

Func<int,int> HelloInst = (param1) =>
  MessageBox.Show("Hello delegate World"
                         + param1.ToString());
  return ++param1;

Using Action or Func you can create a delegate that can encapsulate almost any lambda expression but notice that there it might still be better to define your own delegate to convey the meaning of what the lambda is supposed to do.

The need to convey a meaning is the motivation behind there being a number of other standard predefined delegates as well as the Action and Func delegates.

For example, a predicate in mathematical logic is a function which evaluates to true or false i.e. a function returning a boolean. The Predicate<T> delegate can be used to wrap a lambda that accepts a single parameter and returns a boolean. That is Predicate <T> is identical to Func<T><bool>.

Similarly the Comparison<T> delegate takes two input parameters, x, y say,  of the same type and returns an int that indicates the relative "size" of the two objects - negative means x<y, zero means x=y and positive means x>y. For example

Comparison<int> Bigger(x,y)=>
    if(x<y) return -1;
    if(x=y) return 0;
    return 1;

There is also a Converter<Tin,Tout> delegate which represents a method that converts the input type to the output type:

Convertor<int,string> MyConv (x,y)=>
 return x.ToString();

There are lots of other predefined delegates but they rapidly become increasingly specialized like the EventHandler<TEventArgs> delegate.

Expression lambdas

A statement lambda can have a mix of expressions and statements. However there is a particularly simple form of the lambda that is very common in other languages.  An expression lambda" has only a single expression as its body and simply returns the result of the expression:


For example:

x => x*x;

is an expression lambda that takes x and squares it. Notice that there is only one parameter the parentheses are optional.

The one problem with expression lambdas is that they can look more complicated than they are because they often make use of comparison operators. For example  the confusing looking:

x => x <= 10;

defines a lambda expression that returns true if x is smaller than or equal to 10 and false otherwise even though it looks like an expression for crushing an x between itself and 10. 

Notice that expression lambdas are ideal for passing short chunks of code, Boolean conditionals for example, to other methods which is what they were designed for.

Expression lambdas are used extensively in the framework classes where there are a number of where the standard delegate types often make this easier. For example the Array type has a static Find method which accepts an array and a predicate and returns the first element that makes the predicate true.  For example

int i=Array.Find<int>(MyIntArray, x => x>0);

returns the first element in MyIntArray that is positive. 

In short expression lambdas are ideal for passing functions into methods.

In C#6 they can also be used to define a method. For example:

public int square(int x) => x * x;

You can use the same syntax to define a getter only property:

public int total => t1 + t2;

When you use total the expression is evaluated to provide the value.

Slightly more esoteric is the use of a lambda in an indexer:

public MyClass this[int i] => myarray[i]

which will return an instance of MyClass stored in myarray[i] when you use an index on an instance of the class you are defining. For a short but unrealistic example we define the class:

class myArray
 private string[] myarray= { "test0", "test1" };
 public string this[int i]=>myarray[i];

Now we can create an instance and use the indexer:

myArray myArrayObject = new myArray();

Expression Trees

An expression lambda is also special because it can be converted to an expression tree.

What is an expression tree?

Put simply an expression tree is just an object which contains all of the information contained in the lambda. It is a representation of the function in data.

Why would you want to create an expression tree?

An expression tree can be stored or transmitted to another system where it can be implemented at a later time or remotely. You can think of an expression trees as a data exchange format for lambdas but they also allow you to create lambdas dynamically. You can create an expression tree without using a lambda and then use it to create the method that corresponds to the lambda. That is the expression tree is one way of dynamically generating a method.

The main reason that expression trees were introduced was so that LINQ which makes heavy use of expression lambdas could turn a query into a data structure and send this "over the wire" to a remote server but there are no doubt lots of alternative and innovative uses just waiting to be discovered.

To see expression trees in action, let's take a simple expression lambda and convert it into an Expression object. When an expression lambda is assigned to an Expression variable it is automatically converted to an expression tree. For example:

Expression<Func<int, int>> ExTree = (x) => x * x;

Notice that you have to specify the delegate type that the Expression object is going to represent - in this case Func<int,int>. Following this instruction ExTree contains a data representation of the expression lambda. 

You can explore the expression tree using its methods and properties. For example:


results in

(x * x)

You can apply the method in an expression tree using the Compile method. For example:

Func<int, int> MyNewDelegate = ExTree.Compile();
int result=MyNewDelegate(3);

stores the expression lambda in MyNewDelegate and then uses it. You can also create the delegate on the fly:

int result= ExTree.Compile()(3)

Last Updated ( Thursday, 22 September 2016 )