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