IEnumerable<> and IEnumerable

written by Ryan Olshan on Monday, May 08 2006

I've answered this 2x in the past week, so I think it's a worthy point to bring up. When implementing generic interface IEnumerable<>, you'll need to implement both IEnumerable<>.GetEnumerator() and IEnumerable.GetEnumerator() as IEnumerable<> inherits IEnumerable. Otherwise, you'll get the below error message:

'xxx' does not implement interface member 'System.Collections.IEnumerable.GetEnumberator()'. 'xxx' is either static, not public, or has the wrong return type.

As for why IEnumerable<> inherits IEnumerable, the best answer I could come up with is because it can.

So, to sum things up:

using System.Collections;

using System.Collections.Generic;

 

public class MyClass : IEnumerable<SomeType>

{

    public IEnumerable<SomeType> GetEnumerator()

    {

        // Code here

    }

 

    public IEnumerable GetEnumerator()

    {

        // Code here

    }

}

Kick this post on .NET Kicks

Similar Posts

  1. 911 Pigeon Alert
  2. Implicit and Explicit Operators in C#
  3. What's wrong with this generic type?

Comments

  • ryanjb2 on on 5.10.2006 at 5:45 PM

    ryanjb2 avatar

    Thanks, that solved the first problem, but now it says that my class already defines GetEnumerator with the same parameter types.

  • Ryan Olshan on on 5.12.2006 at 10:47 AM

    Ryan Olshan avatar

    Could you post the relevant code?

    Ryan

  • ryanjb2 on on 5.12.2006 at 11:07 AM

    ryanjb2 avatar

    public class OrderPaintItem : PaintItem, IEnumerable<PaintComponent>
    {
    private List<PaintComponent> paintComponents = new List<PaintComponent>();

    ......

    public IEnumerable<PaintComponent> GetEnumerator()
    {
    return this.paintComponents.GetEnumerator();
    }

    public IEnumerable GetEnumerator()
    {
    return this.paintComponents.GetEnumerator();
    }
    }

    Sorry if that isn't formatted correctly.

    Originally I only implemented "IEnumerable<>.GetEnumerator()", and I got the error you described in your initial blog entry.  Implementing "IEnumerable.GetEnumerator()" got rid of that but now it complains about two indentical methods with the same argument types.  Thank you for any help.

  • Ryan Olshan on on 5.15.2006 at 7:04 AM

    Ryan Olshan avatar

    Change it to something like:

    public IEnumerable<PaintComponent> GetEnumerator()
    {
        foreach (PaintComponent item in paintComponents)
        {
            yield item;
        }
    }

    HTH,
    Ryan

  • ryanjb2 on on 5.17.2006 at 8:15 AM

    ryanjb2 avatar

    Everything is working fine now.  I did have to use "yeild return item" instead of just "yeild item."

    Thank you for your help.  Previous to this, I had a function that would build a DataTable out of the collection for databinding.  That was a big waste of resources and time.

Post a comment