Treat Code as Data: C#: Defer Execution: Listing 1
The first line of this sample doesn't actually do anything. It builds the structure that creates the sequence one item at a time, as you need it.
public static class MyExtensions
{
public static IEnumerable<T>
Generate<T>(int num,
Func<T> Generator)
{
int index = 0;
while (index++ < num)
{
yield return Generator();
}
}
}
IEnumerable<DateTime> sequence =
MyExtensions.Generate(5,
() => DateTime.Now);
foreach (var time in sequence)
{
Console.WriteLine(time);
System.Threading.Thread.Sleep(9000);
}
System.Threading.Thread.Sleep(9000);
Console.WriteLine("Do it again");
foreach (var time in sequence)
{
Console.WriteLine(time);
System.Threading.Thread.Sleep(9000);
}