Visual Basic(Microsoft): Version 5 & 6 FAQ

VB Programming Concepts

In Java, C#, and VB.Net, using the New keyword on the same line as the declaration statement actually causes the object to be instantiated. Not so with VB6. In VB6, the As New syntax creates an "auto-instancing" object variable. In other words, the code line

CODE

Dim myObj as New myClass

requires the VB compiler, every time myObj is referenced, to check and see if myObj is Nothing and if so to create an instance of myClass. So, the code

CODE

While there are some circumstances in which the use of the former syntax is preferable to the latter, they are few and far between. For example, if you had a large number of instances of another object that only in certain circumstances ever used this object, and when they did only called one method of the object one time, it might make sense not to instantiate the object unless the code referenced it to avoid unnecessary memory overhead.

However, the time that you will see this most often is when the object is only referenced once, especially in conjuction with the With keyword. For example:

CODE

This will only actually instantiate the object once, at the time it is encountered in the with statement. Of course, you don't really need to use a myObject variable in this case; it's more a matter of style. You can also do it this way:

CODE

In effect, this is also an auto-instancing variable, since an instantiated class reference is implied (and created) by the "with new" statement. This is actually even more efficient, as it isn't storing a variable definition throughout the life of the procedure in which it's declared.