Here is a better example of using an anonymous delegate that proves, in my mind, that they are lexical closures. I sure hope my definition of closures is correct ;)
Here's the code. Please do guess what it does or better yet, compile and run it. The important aspect is to guess which values of "s" do or do not match.
using System;
using System.Threading;
namespace AnonDelegateTest2
{
class Program
{
delegate void FunkyDelegate();
static void Main(string[] args)
{
FunkyDelegate fd = GetDelegate();
for (Int32 i = 0; i < 10; i++)
{
fd();
}
}
static FunkyDelegate GetDelegate()
{
String s = DateTime.Now.Ticks.ToString();
FunkyDelegate fd = delegate()
{
Console.WriteLine("Entering fd");
Console.WriteLine(s);
s = DateTime.Now.Ticks.ToString();
Thread.Sleep(100);
Console.WriteLine(s);
Console.WriteLine("Leaving fd");
Console.WriteLine();
};
return fd;
}
}
}