tags:

views:

84

answers:

2

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.

+2  A: 

Add the line:

using System.Collections;

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

Kobi
I added that line and: ... ConsoleApplication1.Sequence' does not implement interface member 'System.Collections.Generic.IEnumerable<ConsoleApplication1.MyClass>.GetEnumerator()'
nik
@nik: Getenumerator method should be called GetEnumerator. C# is case sensitive.
Bear Monkey
A: 

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.

Noldorin
no, no good. ConsoleApplication1.Sequence' does not implement interface member 'System.Collections.Generic.IEnumerable<ConsoleApplication1.MyClass>.GetEnumerator()'
nik
No idea what you're doing wrong, but why not just use the VS smart tag to auto-implement the interface? Guaranteed to get things right then.
Noldorin
@Noldorin, I want to implement generics --> IEnumerable<T> but it seems there's no samples. All things that i can find is all about IEnumerable. Can you give me any example of IEnumerable<SomeClass> with internal collection for example List<SomeClass> _elements;
nik
There is a typo in your code: Its GetEnumerator not Getenumerator (casing is important).
Albic
Ahhhhhhhhhhhhhhhhhhhh :-) thanks Albic
nik
Hah, wasn't even looking at that function. Good spot.... always the silliest mistakes.
Noldorin