Friday, April 8, 2011

Whats the problem with my generic collection?

I wrote a class which imports System.Collections.ObjectModel. For the management of the collection, I've written:

Default Public ReadOnly Property Item(ByVal vntIndexKey As Integer) As ItemType
        Get
            Return CType(mCol.Item(vntIndexKey), ItemType)
        End Get
 End Property

Then when i was debugging, I was told:

"Index was out of range. Must be non-negative and less than the size of the collection."

The "ItemType" is always being an object, and during the debug, I can see that vntIndexKey=1.

Could someone tell me why?

From stackoverflow
  • There is nothing syntactically wrong with your code. It appears that the problem is you are attempting to access an element that does not exist in the collection. The underlying collection class is saying that element "1" is beyond the range of the collection. Only 0-(collection.Count-1) are valid indexes.

    How many items are in the collection?

    JaredPar : Are you using 1 or 0 in the watch window?
    JaredPar : Yes, if there is only 1 element then 0 is the only valid index.
  • How many items are in the collection at the time? Be sure to check that the index is greater or equal to the lower bound and less than or equal to the upper bound.

  • Good chance that you have nothing in your collection

  • Thanks a lot. But i dont understand, why if i use a collection, there is a "Empty placeholder to adjust for 1-based array" but not for the generic collection?

  • You may experiment a bug that appeared with the 3.5 SP1:

    https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361539

0 comments:

Post a Comment