Microsoft KB Archive/814320

= BUG: &quot;Index was out of range&quot; error message when you access a Visual Basic .NET 2002 collection object that implements IList with -1 Base =

Article ID: 814320

Article Last Modified on 5/11/2007

-

APPLIES TO


 * Microsoft Visual Basic .NET 2002 Standard Edition

-





Beta Information
This article discusses a Beta release of a Microsoft product. The information in this article is provided as-is and is subject to change without notice.

No formal product support is available from Microsoft for this Beta product. For information about how to obtain support for a Beta release, see the documentation that is included with the Beta product files, or check the Web location from which you downloaded the release.



SYMPTOMS
When you use the IList interface with a Visual Basic .NET collection object in Visual Basic .NET (2002) before you use the Insert property, you can insert elements in the list at index -1. If you insert an element at index -1, you receive the following error message when you try to read the element by using the Item property at index -1:

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



CAUSE
The IList index has a base of -1 instead of zero. Therefore, you can insert an element at index -1 even though MSDN documentation states that the IList index is zero-based. However, you receive an error when you try to read the value from the IList at index -1.



WORKAROUND
To work around this bug in Visual Basic .NET (2002), only use a -1 base index only to insert the element. Use a zero base index when you call other properties and methods, such as the Item property and the RemoveAt method.



STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article. This bug was corrected in Microsoft Visual Basic .NET version 2003.



Steps to Reproduce the Behavior
 Open Visual Studio .NET (2002). On the File menu, point to New, and then click Project. Under Project Types, click Visual Basic Projects. Under Templates, click Console Application. Name the project TestIList, and then click OK.

By default, Module1.vb is created.</li>  Add the following code to Sub Main method: Dim col As New Collection Dim i As IList i = col i.Insert(-1, &quot;First Element&quot;) MsgBox(i.Item(-1)) </li> On the Debug menu, click Start to run the application.</li>  Replace the last line of code in the Sub Main method with the following code: MsgBox(i.Item(0)) </li> On the Debug menu, click Start to run the application.</li></ol>

<div class="references_section">