Dim...As New

Dim As New

You will encounter upgrade issues with the As New syntax in two types of cases. The first is when you use As New to declare a variable. The second is when you use it to declare an array. The use of As New to declare a variable is still supported in Visual Basic .NET, but it no longer supports implicit declaration. Array declaration with As New is not supported at all. The following code shows how the Upgrade Wizard handles both types of declarations.

Here are the declarations in Visual Basic 6:

Dim x As New Class1 Dim y(5) As New Class2

Here s how the Upgrade Wizard handles the declarations:

Dim x As New Class1() 'UPGRADE_WARNING: Arrays can't be declared with New. Dim y(5) As New Class2()

Notice that the Upgrade Wizard leaves the array declaration alone. When you first upgrade the project, there will be a compiler error on this line because As New is no longer supported for arrays. The best way to deal with this situation is fairly simple: initialize your array in a loop.

Dim y(5) As Class2 For i = 0 To 5    y(i) = New Class2() Next

This solution does not address the other side of the As New behavior: implicit instantiation. For example, the following code will fail in Visual Basic .NET with a NullReferenceException at run time:

Dim x As New Object1() x.AnyMethod() x = Nothing x.AnyMethod() ' This will cause a NullReferenceException

The Upgrade Wizard will help you isolate these problems. First it will insert a warning wherever you have declared an array with As New. It will also generate another warning wherever you set an object to Nothing. You can use these warnings to track down spots in your code where you might run into difficulties. The only way to resolve these problems is to explicitly create a new instance of Object1 or to test for Nothing whenever you access a variable that might have been set to Nothing.

Dim x As New Object1() x.AnyMethod() x = Nothing x = New Object1() x.AnyMethod()

As New is an example of a language feature that differs significantly in functionality from Visual Basic 6 to Visual Basic .NET. It can present a host of issues in an application that relies too closely on its previous behavior. Watch yourself.



Upgrading Microsoft Visual Basic 6.0to Microsoft Visual Basic  .NET
Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET w/accompanying CD-ROM
ISBN: 073561587X
EAN: 2147483647
Year: 2001
Pages: 179

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net