Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to initialize shared members in a class in VB.NET?

I was looking on the Internet to see if there were any good examples on how to initialize shared members within a class while still initializing instance variables. I did find an expression that might fit to the answer:

Shared Sub New()
    'Declare shared members
End Sub

But you also have the standard

Sub New()
    'Declare instance members
End Sub

How do I initialize both instance and shared members without re-initializing the shared members every time an object is created from a class?

like image 764
Chad Harrison Avatar asked Aug 23 '11 19:08

Chad Harrison


People also ask

How can you initialize a class member within a class?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.

What is shared members in VB net?

Shared Members of a VB.Net Class When we declare a member of a class as Shared, it means no matter how many objects of the class are created, there is only one copy of the member. The keyword Shared implies that only one instance of the member exists for a class.

What is initialization in VB net?

Variable Initialization in VB.NetVariables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is − variable_name = value; for example, Dim pi As Double pi = 3.14159.

How do you initialize a class?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.


1 Answers

Shared Sub New (also known as a type constructor) is executed only once for each type (within an AppDomain, that is), so any member initialization in there will not be be repeated for each instance.

like image 56
Fredrik Mörk Avatar answered Oct 01 '22 18:10

Fredrik Mörk