Treat Code as Data: C#: Introducing Closures and Bound Variables: Listing 2

What a difference restructuring can make. In this version, the compiler has created a closure containing one bound variable: Current. That bound variable is returned for every item in the sequence. Furthermore, changes made to the bound variable are reflected next time you enumerate the sequence.

DateTime current = DateTime.Now;

IEnumerable<DateTime> sequence = 
   MyExtensions.Generate(5, () => current);

foreach (var time in sequence)
{
   Console.WriteLine(time);
   System.Threading.Thread.Sleep(9000);
}

System.Threading.Thread.Sleep(9000);

current = DateTime.Now;
Console.WriteLine("Do it again");

foreach (var time in sequence)
{
   Console.WriteLine(time);
   System.Threading.Thread.Sleep(9000);
}
comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.