Is there a way to make a constructor for a shared
class in VB.NET? I do it all the time in C# as follows, but I can't seem to get it to work in VB.NET.
static class someClass
{
public static string somePublicMember;
static someClass()
{
messageBox.show("I just constructed a static class");
}
}
When the following code is executed, the constructor will be called.
...
someSillyClass.someSillyPublicMember = 42;
...
Can a static
(shared
) class even have a constructor in VB.NET?
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.
Static classes cannot contain an instance constructor. However, they can contain a static constructor.
A constructor in VB.NET is defined as a procedure that has the name New (rather than Initialize as in VB 6.0) and can accept arguments to allow clients to pass data into the instance to assist with initialization. Constructors do not return values and therefore are always declared as a Sub.
Static class can have static constructor with no access modifier and must be a parameter less constructor,since static constructor will be called automatically when class loads , no point of passing parameters. We can not create constructor of static class, however we can create static constructor for Non static class.
Read documentation here. In you can do
Shared Sub New()
...
End Sub
And it will be invoked. From MSDN:
Shared constructors are run before any instance of a class type is created.
Shared constructors are run before any instance members of a structure type are accessed, or before any constructor of a structure type is explicitly called. Calling the implicit parameter less constructor created for structures will not cause the shared constructor to run.
Shared constructors are run before any of the type's shared members are referenced.
Shared constructors are run before any types that derive from the type are loaded.
A shared constructor will not be run more than once during a single execution of a program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With