Difference between revisions of "As New"

From HashVB
Jump to: navigation, search
m (Damn spelling...)
m (Added VB6 header)
Line 1: Line 1:
 +
{{VB6}}
 
As New is a feature of VB's Dim statement that saves you having to explicitly "create" an object. This is OK at times, but can lead to problems:
 
As New is a feature of VB's Dim statement that saves you having to explicitly "create" an object. This is OK at times, but can lead to problems:
  

Revision as of 14:05, 9 November 2005

float
 This article is based on Visual Basic 6. Find other Visual Basic 6 articles.

As New is a feature of VB's Dim statement that saves you having to explicitly "create" an object. This is OK at times, but can lead to problems:

  • VB puts an implicit "If Object Is Nothing Then Set Object = New OpjectType" before every use, including destruction. It is inefficient and not necessary.
  • If you release the object, ANY reference to it later on will cause it to be recreated again.

The latter can lead to hard to track down problems where it's been released but you try an use it afterwards and it is not in a state you expect. If you don't use As New, you will get an error alerting you to fix your code.

It is better to use Dim Object As ObjectType and use Set Object = New ObjectType on initialisation before you first try and use it.