Export (0) Print
Expand All
Expand Minimize

Array variables cannot be declared with New

Visual Studio .NET 2003

In Visual Basic 6.0, array variables could be declared with the New keyword; this would automatically initialize all members of the array.

In Visual Basic .NET the New keyword is no longer supported for arrays; members within an array must be explicitly initialized.

The following example shows an array declared with the New keyword:

' Visual Basic 6.0
Dim MyArray(1) As New Class1
MyArray(0).Text = "Hello"
MyArray(1).Text = "world"

' After upgrade to Visual Basic .NET
' UPGRADE_WARNING: Arrays can't be declared with New.
Dim MyArray(1) As New Class1
MyArray(0).Text = "Hello"
MyArray(1).Text = "world"

What to do next

  • Remove the New keyword.
  • Initialize all members of the array when the array is declared:
    ' Modified code
    Dim MyArray(1) As Class1
    MyArray(0) = New Class1
    MyArray(1) = New Class1
    MyArray(0).Text = "Hello"
    MyArray(1).Text = "world"
    
  • Alternatively, you can initialize the members of the array when they are used; however, if you do so, you should test to ensure that they are not already initialized:
    If IsNothing(MyArray(1)) Then
       MyArray(1) = New Class1
    End If
    MyArray(1).Text = "world"
    

See Also

Array Size Declaration Changes in Visual Basic

Show:
© 2014 Microsoft