BUG: "Index was out of range" error message when you access a Visual Basic .NET 2002 collection object that implements IList with -1 Base (814320)



The information in this article applies to:

  • Microsoft Visual Basic .NET (2002)

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.

MORE INFORMATION

Steps to Reproduce the Behavior

  1. Open Visual Studio .NET (2002).
  2. On the File menu, point to New, and then click Project.
  3. Under Project Types, click Visual Basic Projects.
  4. Under Templates, click Console Application.
  5. Name the project TestIList, and then click OK.

    By default, Module1.vb is created.
  6. Add the following code to Sub Main method:
          Dim col As New Collection()
          Dim i As IList
          i = col
          i.Insert(-1, "First Element")
          MsgBox(i.Item(-1))
  7. On the Debug menu, click Start to run the application.
  8. Replace the last line of code in the Sub Main method with the following code:
    MsgBox(i.Item(0))
  9. On the Debug menu, click Start to run the application.

REFERENCES

For more information, visit the following MSDN Web site:

Collections in Visual Basic .NET
http://msdn.microsoft.com/library/en-us/vbcn7/html/vbconcollectionsinvisualbasic.asp

Modification Type:MinorLast Reviewed:1/20/2006
Keywords:kbvs2005swept kbvs2005doesnotapply kbfix kbCollectionClass kbCollections KB814320 kbAudDeveloper