VB Migration Partner

KNOWLEDGE BASE - Forms and controls


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 




Follow Francesco Balena on VB6 migration’s group on

LinkedIn





Read Microsoft Corp’s official case study of a VB6 conversion using VB Migration Partner.




Code Architects and its partners offers remote and onsite migration services.

More details




Subscribe to our free newsletter for useful VB6 migration tips and techniques.

newsletter



To learn more about your VB6 applications, run VB6 Analyzer on your source code and send us the generated text file. You will receive a detailed report about your VB6 applications and how VB Migration Partner can help you to quickly and effectively migrate it to .NET.

Get free advice



A fully-working, time-limited Trial Edition of VB Migration Partner allows you to test it against your actual code

Get the Trial




The price of VB Migration Partner depends on the size of the VB6 application, the type of license, and other factors

Request a quote




Migrating a VB6 application in 10 easy steps

Comparing VB Migration Partner with Upgrade Wizard

Migration tools: Feature Comparison Table

All whitepapers