HOWTO: Determine When the Initialize Event of Class Gets FiredLast reviewed: July 14, 1997Article ID: Q154651 |
The information in this article applies to:
SUMMARYWhen you create an instance of one of your class modules in Visual Basic 4.0 code, the Initialize event is the first operation that occurs. You can use this fact to explore the timing of object creation when you declare object variable As New. Below is some sample code showing how to demonstrate the issue.
MORE INFORMATION
When you declare an object variable using the New keyword, it also contains the special value Nothing. However, the first time the variable is used to invoke a property or method of the class, Visual Basic notices that the variable contains Nothing and creates an instance of the class. The object must be created before the property or method is actually invoked, so the Initialize event precedes the property or method call. This is known as IMPLICIT OBJECT CREATION. If you use Class_Initialize to set global flags, you should use EXPLICIT OBJECT CREATION to make sure you know exactly when the object is declared, so that global flags are set before they are used. This is particularly true if your Class Initialize event performs subtle tasks that may not cause the application to fall over but may affect the outcome of the program. Note, however, that Class_Initialize is a perfectly safe place to initialize class data, because it occurs before any other event or method. There is also a complementary case that can be of interest: Because Class_Initialize always happens before any other event or method is invoked, the following is true:
'Class module code Option Explicit Public NowYouSeeIt As String Private Sub Class_Initialize() MsgBox NowYouSeeIt End Sub 'Form1 code Private Sub Form_Load() Dim c1 As New Class1 c1.NowYouSeeIt = "This won't appear in the MsgBox." End SubIn other words, Class_Initialize must occur even before a public variable is set. Therefore, in the example above, the Class_Initialize event is fired before the value of "NowYouSeeIt" is assigned to the class variable and the message box comes up with no text in the box.
REFERENCESVisual Basic Help File. The Visual Basic Programmers Guide 4.0 Chapter 7, P.200 and P.218. For more information, please see the following articles in the Microsoft Knowledge Base:
ARTICLE-ID: Q138065 TITLE : How to Enforce Initialization of a VB OLE Class Object ARTICLE-ID: Q129449 TITLE : Object Created w/ NEW Instantiated When Passed as Argument |
Keywords : vb4all vb4win kbhowto
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |