locked
IEnumerable and IEnumerable<T> RRS feed

  • Question

  • .NET 2.0/VS 2005 question - How do I implement both IEnumerable and IEnumerable<T>?

    I get an fxcop warning if I implement only IEnumerable, and I want to be a good developer. Here's the warning without IEnumerable<T> implemented:

    "An externally visible type implements the System.Collections.IEnumerable interface but does not implement the System.Collections.Generic.IEnumerable interface, and the containing assembly targets .NET Framework 2.0. This rule ignores types that implement System.Collections.IDictionary"

    Here's my class:

        public class XYZCollection : IEnumerable, IEnumerable<XYZ>
        {
            private ArrayList _XYZs;

            public IEnumerator GetEnumerator()
            {
                foreach (XYZ item in _XYZs)
                    yield return item;
            }

            public IEnumerator<Delivery> GetEnumerator()
            {
                foreach (XYZ item in _XYZs)
                    yield return item;
            }
            ... more code, e.g. logging stuff added /deleted for auditing purposes etc
        }

    When I try to compile this I get an "already defines a member called 'GetEnumerator' with the same parameter types" error message.

    It's driving me nuts - I'm missing something simple what is it please?

    Wednesday, November 30, 2005 8:01 AM

Answers

  • Try this:


    public class XYZCollection : IEnumerable, IEnumerable<XYZ>
    {
        private ArrayList _XYZs;

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

            public IEnumerator<Delivery> GetEnumerator()
            {
                foreach (XYZ item in _XYZs)
                    yield return item;
            }
    }


     



    You may also want to look at replacing your ArrayList with a type-safe List<XYZ>.

     

    Wednesday, November 30, 2005 8:05 AM

All replies

  • Try this:


    public class XYZCollection : IEnumerable, IEnumerable<XYZ>
    {
        private ArrayList _XYZs;

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

            public IEnumerator<Delivery> GetEnumerator()
            {
                foreach (XYZ item in _XYZs)
                    yield return item;
            }
    }


     



    You may also want to look at replacing your ArrayList with a type-safe List<XYZ>.

     

    Wednesday, November 30, 2005 8:05 AM
  • Thanks David, I knew it was something simple. In fact I should've just right clicked on the interfaces and selected "implement". D'oh.
    Thursday, December 1, 2005 2:34 AM