nik
nik

Reputation: 895

Implementing of IEnumerable<T>

I have a code:

    public sealed class Sequence : IEnumerable<MyClass>
    {
        List<MyClass> _elements;

        public IEnumerator<MyClass> Getenumerator()
        {
            foreach (var item in _elements)
            {
                yield return item;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._elements.GetEnumerator();
        }
    }


// ....

Sequence s = new Sequence();

// ...
// filling s with some data
// ...

foreach(MyClass c in s)
{
   // some action
}

That code doesn't want to compile. It DOESNT want to compile. Using the generic type 'System.Collections.Generic.IEnumerator' requires '1' type arguments

Help me to rewrite MyClass to support enumeration.

I tried several combinations, used Google. Everywhere examples of Enumerable and IEnumerator without generics.

Upvotes: 3

Views: 1533

Answers (2)

Noldorin
Noldorin

Reputation: 147290

Sounds like you're just missing a using directive, since IEnumerator (of the non-generic variety) lives in System.Collections, and not System.Collections.Generic (which is included by default at the top of every source file).

So just define:

using System.Collections;

ando you're good to go.

Upvotes: 0

Kobi
Kobi

Reputation: 138017

Add the line:

using System.Collections;

You want to use System.Collections.IEnumerator, not System.Collections.Generic.IEnumerator<T>.

Upvotes: 3

Related Questions