I've been reading this article about closures in which they say:
- "all the plumbing is automatic"
- the compiler "creates a wrapper class" and "extends the life of the variables"
- "you can use local variables without worry"
- the .NET compiler takes care of the plumbing for you, etc.
So I made an example based on their code and to me, it seems as though closures just act similarly to regular named methods which also "take care of the local variables without worry" and in which "all the plumbing is automatic".
Or what problem did this "wrapping of local variables" solve that makes closures so special / interesting / useful?
using System;
namespace TestingLambda2872
{
class Program
{
static void Main(string[] args)
{
Func<int, int> AddToIt = AddToItClosure();
Console.WriteLine("the result is {0}", AddToIt(3)); //returns 30
Console.ReadLine();
}
public static Func<int, int> AddToItClosure()
{
int a = 27;
Func<int, int> func = s => s + a;
return func;
}
}
}
Answer
So the answer to this one is to read Jon Skeet's article on closures that Marc pointed out. This article not only shows the evolution leading up to lambda expressions in C# but also shows how closures are dealt with in Java, an excellent read for this topic.