BUG: You can add a member after a zero index in a Visual Basic .NET collection (818215)



The information in this article applies to:

  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

SYMPTOMS

In a Microsoft Visual Basic .NET collection, you can add a member after a zero index by using the Add method, but the collection is one-based. However, when you add a member after a zero index, the member is added at the first index.

Note In a Microsoft Visual Basic 6.0 collection, you receive a "Subscript out of range" error when you try to add a member after a zero index by using the Add method.

CAUSE

This bug occurs because the collection is implemented as an array with Empty placeholder to adjust for 1 based array as the value for the zero index. This collection implementation allows you to add a member after the zero index.

WORKAROUND

To work around this bug, notice the value of the After parameter. If the value of the After parameter is zero, then raise an "ArgumentOutOfRangeException" exception, as shown in the following code sample:
      Dim col As New Collection()
      Dim pos As Object

      ' Assign the required numeric value for the After position.
      pos = 0
      Try
         If CInt(pos) = 0 Then
            Throw New ArgumentOutOfRangeException()
         Else
            col.Add("MyItem", "MyKey", , pos)
         End If
      Catch e As Exception
         MsgBox(e.Message)
      End Try       

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed in the "Applies to" section.

MORE INFORMATION

Steps to Reproduce the Behavior

  1. Create a New Visual Basic .NET Console Application project.

    By default, Module1.vb is created.
  2. Add the following code to Sub Main:
            Dim col As New Collection
            col.Add("Item1","KEY1")
            'The following statement should fail, because 0 is not a valid index
            'However no Runtime error is observed
            col.Add("Item2", "KEY2", , 0)
            Console.WriteLine(col.Item(1))
            Console.WriteLine(col.Item(2))
            Console.ReadLine()
    
  3. On the File menu, click Save to save the project.
  4. On the Debug menu, click Start to run the project.

REFERENCES

For more information, visit the following MSDN Web sites:

For more information about user-defined collections, click the following article number to view the article in the Microsoft Knowledge Base:

129635 INFO: User-Defined Collections Are 1-Based Not 0-Based


Modification Type:MinorLast Reviewed:5/26/2006
Keywords:kbvs2005swept kbvs2005doesnotapply kbvs2002sp1sweep kbCollectionClass kbCollections kbbug KB818215 kbAudDeveloper