Search code examples
c#sortedlistenumerator

Can't get an enumerator from a SortedList


I have this object :

class Animation
    {
        //[...]
        private SortedList<int,Frame> frames = new SortedList<int,Frame>();
        private IDictionaryEnumerator frameEnumerator = null;

        //[...]

        public void someFunction() {
            frameEnumerator = frames.GetEnumerator(); //throw error
        }

        //[...]

}

I check msn documentation there : http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.getenumerator.aspx, It look like my code is correct but VS say :

cannot convert System.Collections.Generic.IEnumerator>' to 'System.Collections.IDictionaryEnumerator'.


Solution

  • The IDictionaryEnumerator type is used for older non-generic collection types. In this case you have a strongly type collection and it will instead return IEnumerater<KeyValuePair<int, Frame>>. Use that type instead

    private IEnumerator<KeyValuePair<int, Frame>> frameEnumerator = null;
    

    Note: The enumerator type for SortedList<TKey, TValue> does indeed implement the IDictionaryEnumerator interface. If you really prefer that one you can access it with an explicit cast

    frameEnumerator = (IDictionaryEnumerator)frames.GetEnumerator();
    

    I would avoid this route though. It's better to use the strongly typed interfaces and avoid unnecessary casting in the code.