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
            ' ...
        Next 
    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
        Get
            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