Search code examples
c#iteratorc#-3.0

Are Multiple Iterators possible in c=C#?


Are multiple iterators (for a single class or object) possible in C# .NET? If they are, give me some simple examples.

Sorry if the question is not understandable and please make me clear.


Solution

  • You could certainly create different iterators to traverse in different ways. For example, you could have:

    public class Tree<T>
    {
        public IEnumerable<T> IterateDepthFirst()
        {
            // Iterate, using yield return
            ...
        }
    
        public IEnumerable<T> IterateBreadthFirst()
        {
            // Iterate, using yield return
            ...
        }
    }
    

    Is that the kind of thing you were asking?

    You could also potentially write:

    public class Foo : IEnumerable<int>, IEnumerable<string>
    

    but that would cause a lot of confusion, and the foreach loop would pick whichever one had the non-explicitly-implemented GetEnumerator call.

    You can also iterate multiple times over the same collection at the same time:

    foreach (Person person1 in party)
    {
        foreach (Person person2 in party)
        {
            if (person1 != person2)
            {
                person1.SayHello(person2);
            }
        }
    }