Tuesday, August 4, 2009

Constructors for VB.NET Modules

Did you know that you can have a constructor on a module? I first got the notion to try this after thinking about static constructors in C#. In C#, you can do something like this:

class Class1
private static int _magicNumber;

static Class1()
_magicNumber = 4;
So the next thing to try was to test this out in VB.NET:

Module Module1

Sub New()
End Sub

Public Sub Test()
End Sub

Public Sub Test2()
End Sub
End Module
Running this and calling the methods Test / Test2 (in that order) yields this:


So as you might expect, the construct only gets called once, but is called before any members are accessed in the module. Handy!