Delegates

There is allot of confusion gotesing on in the .NET community when it comes to Lambda expressions.
Allot of blog posts out there claiming that Lambdas are simply another way to write delegates, or rather anonymous delegates.

Lambda expressions and delegates are two different things.

Delegates are always delegates.
Even anonymous delegates will always be turned into “normal” delegates in compiled code.

There is a one to one mapping in the source code to the compiled representation of a delegate.

Lambda expressions however, can be compiled into two different things.
They can be compiled into either delegates OR Linq Expression Trees.

In the cases where a lambda expression have been compiled into a delegate, then sure, they result in the same thing.

But since there is no way to know what a lambda expression will be compiled into just by looking at it.

Eg:SomeMethod( x => x.Substring(10) );

By looking at that code, one can ASSUME that it will execute the string method “Substring” once the lambda is invoked.
But there is no way to know for sure unless you know what argument type the “SomeMethod” has.

Eg.void SomeMethod (Func<string,string> func)

In this case we can be certain that the code we pass will be executed exactly as we intended.

But in this case:

void SomeMethod (Expression<Func<string,string>> exp)

We still pass the exact same snippet of code, but we can no longer be certain what will happen with the snipped of code we passed.
It MIGHT be executed the way we assume, but it might just as well be transformed into SQL code or even a Ruby snipped that is saved to disc and then executed in a Ruby engine.

So this is what I consider to be a huge difference between anonymous delegates and lambda expressions.

In the delegate case you can be 100% certain that the code will execute exactly as stated.
And in the lambda case, it might be executed outside of the .NET run-time in some completely different context.

I’ve been planning to write about stateful anonymous delegates for quite some time now so here I go :-)

The common perception of anonymous delegates is that they are stateless functions used for filtering and transformations and similar things.

What is less known is that anonymous delegates can hold state by binding to local variables.
If you create an anonymous delegate inside a factory method, you can infact give the delegate it’s own state.

The above code will print 1, 2, 3 in the console window, simply because the delegate is increasing the value of the bound variable inside it’s body.

So where does anonymous delegates store it’s state?
The state is stored as fields inside a class that is auto generated by the C# compiler.
This class will contain the state for all bound variables / arguments that are used inside anonymous delegates defined inside the same method.

And when is this useful?
To be honest, almost never ;-)
But there are cases where it is actually quite nice.

This code will create a memoization for any delegate of the type Func<T1, T2, TResult>.
You simply pass a delegate to it, and you will get a memoized delegate back.

The code creates a dictionary that will act as our cache.
And then returns a new delegate that are bound to this dictionary.
The returned delegate will transform it’s arguments into a key and then check if the key is present in the cache.
If the key is present, it will return the cached value.
And if not, it will call the wrapped delegate and then store the result in the cache.

You can even pass normal methods as argument to the memoizer and get a delegate that acts as a cache around your method.

Well that’s it :-)
Now go and abuse the mutable variable bindings in your delegates.

In C#3 we can use Linq expression trees to solve this problem to.
I’m not saying that it is a better or faster solution than Oren’s IL emit version.
The IL emit is completely optimized for what it is supposed to do, so its hard to beat.
This is just an alternative if you are a bit affraid of IL emit ;-), Linq expressions are just easier to understand for most people.

So how is it done?
First we need a delegate declaration:

delegate T ObjectActivator<T>(params object[] args);

We will use this delegate in order to create our instances.
We also need a generator that can compile our delegates from expression trees:

“They are not. There have been a few threads on this subject before,
and the conclusion was that it is impossible to perform any of the
built-in mathematical operations on generic types.”

Many have tried to come up with solutions for calculating with generic types, most of them based on provider solutions where you have to provide a “Calculator” class for each type that you want your generic class to support.
Quirky to say the least..

So what does this method do?
The first line in it will create a parameter expression, that is an argument that will be passed into our delegate eventually.

The next line creates a member expression, that is the code that access the field we want to use.
If you look at the code, you will see that we create an expression that access fields (Expression.Field) and that the first arg is the parameter we created before and the 2nd arg is the name of the field we want to access.
So what it does is that it will access the named field on the object that we pass as an argument to our delegate.

The 3rd line is where we create our lambda expression.
The lambda expression is the template for our delegate, we describe what we want to pass into it and what we want to get out of it.

The last part of the code will compile our lambda into a typed delegate: Func<T,R>, where T is the type of the argument we want to pass it and R is the type of the result we want to get out of it.