I was looking for, but could not find, an idiomatic example for a generic class implementing IEnumerable, which does this: constructor takes start
and interval
, and GetEnumerator
returns IEnumerator
, which starts from starts and goes on forever returning items with the interval.
In other words, something like:
public class Sequence<T> : IEnumerable<T> where T :... {
public T start { get; private set; }
public T interval { get; private set; }
Sequence(T start, T interval)
{
...
}
IEnumerator<T> GetEnumerator()
{
for(T n = start ; ; n += interval) // does not compile
yield return n;
}
... what else?
}
There are lots of related questions, and small snippets, bits&pieces, but I have not been able to find a single nice example of a complete class, which does at least something similar enough. This is about how to implement this, so if there is existing class which does just this, it'd be good to know, but not an answer to the question.
So, actual question(s): Which is the most recent C# version that has introduced new features useful for this, and what is the ideal example code to do this with it?
Also if there are any common pitfalls, mistakes which inexperienced C# developers make related to this kind of a class, those would be good to know.
Update: since the exact thing I'm asking for seems impossible, I guess the next best thing is replacing interval
with a lambda for getting the next item, or something like that.