Use Dim As New to Automatically Instantiate ObjectArticle ID: Q138533Creation Date: 23-OCT-1995 Revision Date: 17-NOV-1995
The information in this article applies to:
SUMMARY
When an object is dimensioned "As New," Visual Basic automatically
instantiates the object the first time the object variable is used.
Furthermore, if the object is set to Nothing, another instance will be
instantiated automatically if the object variable is used again.
MORE INFORMATION
To dimension an object "As New," use this syntax:
Dim MyObject As New MyClassIn this case, the first time MyObject is used, an object of MyClass is instantiated. If you set MyObject to Nothing, the next time it is used a new object of MyClass is created. The following code illustrates the behavior:
Dim MyObject As New MyClass ' Dimension new MyObject MyObject.Name = "Bob" ' MyObject is instantiated Set MyObject = Nothing ' MyObject is destroyed Print MyObject.Name ' A new object of type MyClass is createdIn contrast, if you use a two-step creation process, Visual Basic will not automatically create the object if it is set to Nothing. In the two-step creation process, you first dimension the object, and then set it is "Set As New." For example:
Dim MyObject As MyClass ' Dimension MyObject Set MyObject = New MyClass ' Create a new instance of MyClass MyObject.Name = "Bob" ' Set property Set MyObject = Nothing ' Destroy MyObject Print MyObject.Name ' Error -- Object not setIn this case, you receive an error when using an object that is not set instead of a new object being instantiated automatically. Using the two- step creation process makes your code more readable and easier to debug because it requires explicit instantiation of objects.
Step-by-Step Example The following Example illustrates the behavior using the built-in collection object.
|
THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.