Search code examples
c#icollection

implement IEnumerator and IEnumerable in ICollection


I am very new to this ICollection stuff and need some guidance of how to implement the IEnumerable and IEnumerator. I have checked Microsoft documentation and I think I understand what was said there (I think). But when I tried to implement it in my case, I was a bit confused and may need some clarification.

Basically, I declared a class T, then another class Ts which implemented ICollection. In Ts, I have a dictionary.

From the main program, I would like to initialize the class Ts like this: Ts ts= new Ts(){{a,b}, {c,d}};

so, my questions are:

1) is it legal to do that? It appears that it is as the compiler did not complaint although I have not run the test because I have not thoroughly implement IEnumerable and IEnumerator, which brought to my 2nd question

2) How do I implement IEnumerable and IEnumerator?

Below is my pseudo code to illustrate my points.

        public class T
        {
           string itemName;
           int    quantity;
           .....
           public T(string s, int q)
           { 
              .....
           }
        }
        public class Ts: ICollection
        {
            private Dictionary<string, T> inventory= new Dictionary<string,T>();

            public void Add(string s, int q)
            {
                inventory.Add(s, new T(s,q));
            }

             public IEnumerator<T> GetEnumerator()
            { 
            // please help              
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
            // what is the proper GetEnumerator here
            }
            ...
            implement other method in ICollection
        } 

        extract from the main program
        public Ts CollectionOfT = new Ts(){{"bicycle",100},{"Lawn mower",50}};
        .........

Solution

  • The proper implementation is to cast your collection to IEnumerable in the explicit implementation:

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

    For the generic version, call GetEnumerator on your collection:

    public IEnumerator<T> GetEnumerator() {
        return your_collection_here.GetEnumerator();
    }
    

    You must have something that is backing your custom collection.. such as a List, Array, etc. Use that in those implementations.