C# Closures Explained

Thanks to all of the functional goodness that was put into C# 3.0 we have a ton of power at our disposal. Unfortunately with a lot of this power also comes increased complexity. Programmers usually exacerbate the complexity problem, because unfortunately we often like to sound like we are smarter than we actually are.

We often like to use big words and lots of acronyms to scare away the neophytes. Oh crap, there I go again…

Anyways, one of these topics that is blindingly simple is closures. But I continue to see definitions that are as clear as mud to the average developer. Let’s go ahead and look at the Wikipedia definition of a closure:

“In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.”

All clear, right? Well, if it is for you, then super… you can stop reading. But if not, and the next time this topic comes up you want to sound like Super Duper Computer Science Guy™ … then keep reading.

Sir, Your Functions Are First Class

So first, what is a “first-class function”? A first class function simply means that it is a function which your language treats as a first class data type. It means that you can assign a function to a variable, pass it around, and invoke it… just like a normal function. In C# we can create a first class function using anonymous methods:

Func myFunc = delegate(string var1)
return "some value";

Or we can do it using lambdas:

Func myFunc = var1 => "some value";

Both of those are functionally equivalent, and they just create a method that takes a string and returns a string. We can call that method by invoking the variable just like we would any method:

string myVar = myFunc(“something”);

This means that C# supports first class functions, yay!

Like My Variables Free

And so now we have first-class functions with free variables… And what, pray tell, is a free variable? A free variable just happens to be a variable which is referenced in a function which is not a parameter of the function or a local variable of the function. Okay, so it might look like this:

var myVar = "this is good";

Func myFunc = delegate(string var1)
return var1 + myVar;

Okay, so the anonymous delegate is referencing a variable that is in its enclosing scope. That variable isn’t a parameter, and it isn’t a local variable. So it is a free variable.

How Does It Work?

Well, the next question I always ask is, how does it work. And normally when people ask me this question I say “very carefully”, but that is only because I am annoying. In reality this is implemented in a more straightforward manner than you might think. What we are really doing here is binding up a method with some data and passing it around. Geez, I sure do wish we had something like that in C#… oh wait, we do, it is called a class!

You see, the C# compiler detects when a delegate forms a closure which is passed out of the current scope and it promotes the delegate, and the associated local variables into a compiler generated class. This way, it simply needs a bit of compiler trickery to pass around an instance of the compiler generated class, so each time we invoke the delegate we are actually calling the method on this class. Once we are no longer holding a reference to this delegate, the class can be garbage collected and it all works exactly as it is supposed to!

Leave a 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 )

Google photo

You are commenting using your Google 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