VB Migration Partner

KNOWLEDGE BASE - Classes and COM objects

Previous | Index | Next 

[PRB] The VB.NET application throws a NullReference exception (or some other unexpected error) during the initialization phase

The most common cause for a NullReference exception is an auto-instancing (As New) variable that has been translated as-is into VB.NET. Consider the following VB6 code in a .BAS module:

    Public CustomersPath As String
    Public Customers As New CustomerCollection

    Sub Main()
        CustomersPath = "C:\Data"
        For Each cust As Customer In Customers
            ' ...
    End Sub

In this (admittedly contrived) example, the code in the Main method initializes the CustomersPath global variable, which is later accessed from the Class_Initialize event handler of the CustomerCollection class (not shown here). If the code is migrated to VB.NET as-is, the Customers variable is instantiated before entering the Main method, therefore the CustomerCollection’s constructor uses the CustomersPath variable before it is correctly initialized.

The easiest way to avoid this behavior is preserving the auto-instancing semantics of the Customers variable during the migration, which you can do by means of an AutoNew pragma:

    '##Customers.AutoNew True
    Public Customers As New CustomerCollection

which causes the following VB.NET to be emitted:

    Public Property Customers() As CustomerCollection
            If Customers_InnerField Is Nothing Then
                Customers_InnerField = New CustomersCollection
            End If
            Return Customers_InnerField
        End Get
        Set(ByVal Value As CustomersCollection)
            Customers_InnerField = Value
        End Set
    End Property
    Private Customers_InnerField As CustomersCollection
Previous | Index | Next 

Follow Francesco Balena on VB6 migration’s group on


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.


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