tags:

views:

247

answers:

5

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?

+4  A: 

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
Just 1, and i can see that that the index of the item is 0 in the watch
Are you using 1 or 0 in the watch window?
JaredPar
the vntIndexKey is 1, and in the watch window, under the collection mCol, the item(0) is the object. Is this the problem?
Yes, if there is only 1 element then 0 is the only valid index.
JaredPar
Ok, 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?
A: 

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.

Chris Doggett
A: 

Good chance that you have nothing in your collection

Varun Mahajan
A: 

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?

A: 

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

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