Previous | Index | Next 

[PRB] Object variables inside Form_Initialize and UserControl_Initialize events are always Nothing

This article illustrates a minor difference between VB6 and VB.NET in how auto-instancing variables are assigned inside Form_Initialize and UserControl_Initialize events. Consider the following VB6 code:

	' VB6
	Dim col As New Collection

	Private Overrides Sub Form_Initialize()
		col.Add 123
	End Sub

	' [VB.NET]
	Dim col As New Collection    ' same as: Dim col As Collection = New Collection

	Private Overrides Sub Form_Initialize_VB6()
		col.Add(123)
	End Sub

Even though the two code snippets appear to be identical, the semantics are quite different, because VB.NET treats auto-instancing (“As New”) variables as if they were assigned only once inside the constructor of the current class. Because of this minor difference, the VB.NET code throws a NullReference exception when it accesses the col variable.

The problem with form and usercontrol classes is that the Form_Initialize_VB6 and UserControl_Initialize_VB6 methods are actually invoked from inside the constructor of the base class (that is, the VB6Form or VB6UserControl classes), therefore the Collection variable hasn’t been assigned yet.

The easiest workaround for this minor problem is using the AutoNew pragma. When doing so the auto-instancing variable is migrated in such a way that it is never Nothing, and the problem never appears.

More in general, you should keep in mind that the code inside Form_Initialize_VB6 and UserControl_Initialize_VB6 methods is executed before the code inside the constructor of migrated forms and usercontrols. This detail never affects the migrated projects that VB Migration Partner generates, however it might become important if you later add code to the form or usercontrol constructor.

 

Previous | Index | Next