Home > Programming > Local variables are no longer local

Local variables are no longer local

Let us consider this code –

public class MathUtil {

	public static Func<int> MakeIncrementer() {
		int n = 0;

		Func<int> incr = () => ++n;
		return incr;

Given the above code, what do you think should be the output of the below program –

public class Program {

	static void Main(string[] args) {

		Func incr = MathUtil.MakeIncrementer();
		Func incr1 = MathUtil.MakeIncrementer();



Well, if your answer is –


then great, you already know what closures are and don’t need to read any further.

For those of you who don’t – Closures are a block of code with bindings to the environment they come from. Please read this post from Martin Fowler for more details. Also read an excellent article on Functional Programming by Slava. What does bindings and environment mean? In our case, the incr() function, inside the MakeIncrementer function has access (is bound) to the variable n, which is outside the scope (i.e. the environemnt) of the incr() function body.

The most important observations are –

1) That local variables are no longer limited to simple scope rules and have an undefined lifetime.
2) The obvious conclusion is that they’re no longer stored on the stack – they must be stored on the heap instead.

Slava writes this in his article – “Closures bring functional and OO worlds closer together. Every time you create a class that holds some state and pass it to somewhere else, think of closures. A closure is just an object that creates “member variables” on the fly by grabbing them from the scope, so you don’t have to!

And as my friend, Raj mentioned that Java had the notion of inner classes since long back, and they have similar characteristics, I believe closures (implemented with functions) are much less overhead, at least the syntactical part.

Do you still think that local variables are local and stored on the stack  😉

Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: