Things seem a bit slow here, so I thought I share a cool trick I just stumpled upon using C# iterators.
Actually, I'm not sure why it took me so long to come up with it, as it's basically the same thing I've been doing with C++ iterators for about 10 years.
Let's say we want to fill a List with the numbers from 1 to 100. There's no simple way. You'd have to write a loop:
List myList = new List();
for(int i = 1; i<=100; ++i)
myList.Add(i);
But, Lists can be initialized from a IEnumerator. The intention was to allow copying one list into another, but as long as its an IEnumerable, we can work with it:
List myList(Filler.IntFill(1, 100));
WIth the Filler class defined as:
public class Filler
{
static public IEnumerable
IntFill(int start, int end, int step)
{
for (int i = start; i <= end; i += step)
{
yield return i;
}
}
static public IEnumerable IntFill(int start, int end)
{
return IntFill(start, end, 1);
}
}
The trick is to recognize that while iterators are intended to step through a containter, as long as they return a value, it doesn't matter where that value came from.
Also, I would have really liked to have made that a generic class, except there's no way say that generic type T understands +=. (we gotta get MSFT to fix that.....)
Truth,
James