Wednesday, June 27, 2007

What IS a closure?

"Anonymous methods are not closures," is the refrain I've heard when I tell people that .NET supports closures.

Ian Griffiths thinks otherwise, and I agree.

If you don't believe me, go read up on it for your self.

A more apropos question would be--what are closures useful for in day-to-day programming?

Here's one guys attempt to answer that question, at least for the Ruby programmer. I've taken his example and turned it into C#. You really have to get to the point where closure are as accessible to you as a for loop or an if statement before you have the epiphany that make the question above seem droll.


delegate void LogDelegate(string message);
void DoSomething()
{
LogDelegate logger;
SerialNumber serialNumber = NextSerialAndLog(out logger);

logger("process 1");
logger("process 2");
logger("process 3");
}

SerialNumber NextSerialAndLog(out LogDelegate l)
{
sn = new SerialNumber();
l = delegate(string message)
{
LogInfo("DoSomething", sn, message);
};
return sn;
}

No comments: