GetEnumerator returns a Specified cast is not allowed error

G

Guest

I have been asked to change an existing program which Implemented a
Collection Class

The current class had what is below (its just a summary of the code)

Public Class FieldList
Implements System.Collections.IEnumerable

Private thisColl As Collection

Private Sub New()
thisColl = New Collection
End Sub

Public Function GetEnumerator() As System.Collections.IEnumerator
Implements System.Collections.IEnumerable.GetEnumerator
GetEnumerator = thisColl.GetEnumerator
End Function
....
End Class

I wanted to use a SortedList instead of a Collection so changed it such:

Private thisColl As SortedList

Private Sub New()
thisColl = New SortedList
End Sub


After making a couple more changes to where we were adding elements, it
compiled, but when I use a for each statement, I get an error, after the
GetEnumerator is called.
"Specified cast is not allowed"

Any help would be appreciated.
 
B

billsahiker

Sounds like your SortedList had elements of different types, one of
which was incompatible with the item you were iterating with in the
for-each. To avoid this, use the generic version of the SortedList.
 
G

Guest

Thanks for your help. I ended up going in a different direction. I was
trying to take advantage of the GetEnumerator and use a foreach statement
with the SortedList like I did with a Collection, but ended up just using the
SortedList and using the for statement, which actually turns out to be faster
than the foreach statement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top