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:-
Module Module1
Sub Main()
Dim con As New Constructor("Hello world")
Console.WriteLine(con.display())
'display method
End Sub
End Module
Public Class Constructor
Public x As String
Public Sub New(ByVal value As String)
'constructor
x = value
'storing the value of x in constructor
End Sub
Public Function display() As String
Return x
'returning the stored value
End Function
End Class
Output:- Hellow world
Shared Constructor:-"Shared constructor are most often used to initialize class level data such as shared fields"
coding for shared constructor:-
Module Testcons
Sub Main()
Console.WriteLine("100")
B.G()
Console.WriteLine("200")
End Sub
End Module
Class A
Shared Sub New()
Console.WriteLine("Init A")
End Sub
End Class
Class B
Inherits A
Shared Sub New()
Console.WriteLine("Init B")
End Sub
Public Shared Sub G()
Console.WriteLine("Hello world")
End Sub
End Class
Output: 100
200
Hello world
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.