Microsoft KB Archive/818215

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

Article ID: 818215

Article Last Modified on 5/16/2007

-

APPLIES TO


 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-





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 &quot;ArgumentOutOfRangeException&quot; 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(&quot;MyItem&quot;, &quot;MyKey&quot;,, 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 &quot;Applies to&quot; section.



Steps to Reproduce the Behavior
 Create a New Visual Basic .NET Console Application project.

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

<div class="references_section">