.NET Stateful delegates and memoization

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.


static Func<int> CreateCounter() 
     int i = 0; //bind delegate to a local mutable variable 
     return () => i++; 

     //"i" doesn't really go out of scope here 
     // because it is bound to our delegate 

By using this method we can now create a stateful delegate:

var myCounter = CreateCounter(); 
Console.WriteLine( myCounter() ); //prints : 0 
Console.WriteLine( myCounter() ); //prints : 1 
Console.WriteLine( myCounter() ); //prints : 2

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.

Here is a sample that I came up with after reading Ayendes blog ( http://www.ayende.com/Blog/archive/2008/06/04/Review-Umbrella-project.aspx )
He wrote about “memoization” and I thought that would make a great example of stateful delegates.

We can create memoizations in C# by exploiting the fact that anonymous delegates bind to local variables.


static Func<T1, T2, TResult> CreateMemo
    <T1, T2, TResult>(Func<T1, T2, TResult> source)
    var cache = new Dictionary<string, TResult>();
    return (arg1, arg2) =>
               string key = string.Format("{0}|{1}", arg1, arg2);
               if (!cache.ContainsKey(key))
                   var value = source(arg1, arg2);
                       ("Returning {0} and adding it to cache", value);
                   cache.Add(key, value);
                   return value;
                   var value = cache[key];
                       ("Returning {0} from cache", value);
                   return value;

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.



1 Comment

  1. Matthew Davey says:

    Funnily enough I came across this blog (12 years later) after searching ‘stateful delegates’ for a proto.actor project I’m working on. I’m interested in associating state with a behaviours I’m passing to Behaviour.Become and Behaviour.BecomeStacked, rather than just stateless Receive delegates. I’ll give this technique a try!

Leave a Reply to Matthew Davey Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s