Constructor in VB.NET
In this article we will describe the Constructor.
Constructor:-A Constructor is a special kinds of member function that used to initialize the object .
A constructor is like a method in that it contain executable code and may be defined with parameter.
this is first method that is run when an instance of type is created. constructor is two types in VB.NET
- Instance constructor
- Shared constructor
Instance constructor:-"An Instance constructor runs whenever the CLR creates an object from a class"
coding for instance constructor:-
Dim con As New Constructor("Hello world")
Public Class Constructor
Public x As String
Public Sub New(ByVal value As String)
x = value
'storing the value of x in constructor
Public Function display() As String
'returning the stored value
Output:- Hellow worldModule Testcons
Shared Constructor:-"Shared constructor are most often used to initialize class level data such as shared fields"
coding for shared constructor:-
Shared Sub New()
Shared Sub New()
Public Shared Sub G()
Note: Some important points for shared constructor
- 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.