3

I was wondering where in the lifetime of the program a variable that is in a module would be initialized as in this example:

Module Helper
    Friend m_Settings As New UserSettings()

    Sub Foo()
        '...
    End Sub

    Sub Bar()
        '...
    End Sub

End Module

Public Class UserSettings
    Public Property UserName As String
    Public Property PrefServer As Integer

    Public Sub New()
        '...
    End Sub

    Public Sub LoadSettings()
        '...
    End Sub
End Class

When would m_Settings be initialized? I can set a break point at the constructor for UserSettings and look at the call stack, but I see "External Code" in there but that doesn't tell me a lot.

Cuthbert
  • 2,908
  • 5
  • 33
  • 60

1 Answers1

10

The CLR has no direct support for VB.NET modules, it requires all methods and variables to be part of a type. So the VB.NET compiler actually generates a class under the hood. All of the functions you wrote in the module become static methods of that class. All of the variables you declared in the module become static fields of the class.

Any variables that are initialized in your module causes a static constructor to be generated. And the initialization code is moved into this constructor.

Now CLR rules apply: a soon as the jitter touches any of the members of this class, the CLR runs the static constructor. Which then initializes all of the module variables. Which is also why you see [external code] on the call stack, the call originated inside the CLR.

It is rare to have problems with this, the static constructor guarantee in the CLR is a very strong one. About the only tricky mishap is a variable initializer that causes an exception to be thrown. That's when the guts start showing. The stack trace is pretty mystifying since it shows code that doesn't exist in your source code. The actual exception thrown is a TypeInitializationException, very mystifying since you didn't write any type, you need to look at its InnerException to find the real reason.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536