Can the same thing be done in C++/CLI? There's no yield keyword, so my gut reaction is that there isn't, which sucks, but what can you do?
yield return
in C# is just a shortcut that lets the compiler generate the necessary code for you that implements an implementation of IEnumerable<T>
and IEnumerator<T>
. Since C++/CLI doesn't offer this service, you've got to do it manually: just write two classes, one that implements each interface (or, doing it like the C# compiler, one class implementing both but this can get messy if the whole thing can be called repeatedly – cue: statefulness).
Here's a small example – since I don't have an IDE and my C++/CLI is a bit rusty, I'll give it in C#:
class MyRange : IEnumerable<int> {
private class MyRangeIterator : IEnumerator<int> {
private int i = 0;
public int Current { get { return i; } }
object IEnumerator.Current { get { return Current; } }
public bool MoveNext() { return i++ != 10; }
public void Dispose() { }
void IEnumerator.Reset() { throw new NotImplementedException(); }
}
public IEnumerator<int> GetEnumerator() { return new MyRangeIterator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
// Usage:
foreach (int i in new MyRange())
Console.WriteLine(i);