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()
Debug.WriteLine("New")
End Sub
Public Sub Test()
Debug.WriteLine("Test")
End Sub
Public Sub Test2()
Debug.WriteLine("Test2")
End Sub
End Module
Running this and calling the methods Test / Test2 (in that order) yields this:New
Test
Test2
So as you might expect, the construct only gets called once, but is called before any members are accessed in the module. Handy!
No comments:
Post a Comment