Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class constructor in VB

Tags:

c#

vb.net

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?

like image 945
AppFzx Avatar asked Jul 23 '13 14:07

AppFzx


People also ask

What is a static constructor?

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.

Can we have constructor in static class?

Static classes cannot contain an instance constructor. However, they can contain a static constructor.

What are constructors in VB?

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.

How do you create a static constructor in a class?

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.


Video Answer


1 Answers

Read documentation here. In you can do

Shared Sub New()
...
End Sub

And it will be invoked. From MSDN:

  1. Shared constructors are run before any instance of a class type is created.

  2. 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.

  3. Shared constructors are run before any of the type's shared members are referenced.

  4. Shared constructors are run before any types that derive from the type are loaded.

  5. A shared constructor will not be run more than once during a single execution of a program.

like image 50
Ehsan Avatar answered Oct 16 '22 20:10

Ehsan