Constructor in vb.net

Satyapriyanayak
Posted by Satyapriyanayak under VB.NET category on | Points: 40 | Views : 4084
We will know how to use constructor and destructor in a windows application. 

Constructor

Constructor is special method, which controls over the initialization of object. It is used for variable initialization. When we create an object of the class then the constructor within the class is automatically called. It is used with the keyword new before sub in vb.net

There are two types of constructor
1.Shared constructor
2.Instance constructor

Shared constructor: -

1.It is used to initialize only shared variables.
2.These are run only once during a single execution.
3.These constructors always get first preference in comparison to instance constructor.
4.These are used by the keyword shared before sub new.
5.It cannot take parameters.

Instance constructors: -
1.They are used to initialized instance variable ex dim, public, protected, friend, protected friend and private variable.
2.It can also initialize shared variable.
3.It can take parameters.

Ex: - How to declare Instance and shared constructors

Public Class raj
Public Sub New()
MsgBox("Instant constructor of raj")
End Sub
Shared Sub New()
MsgBox("Shared constructor of raj")
End Sub
End Class



Ex
Public Class Form1
Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As New raj
a.kunal()
Dim b As New rahul("pintu")
Dim c As New rahul(10, 10)
End Sub
Public Class raj
Public Sub New()
MsgBox("Hello raj constructor")
End Sub
Public Sub kunal()
MsgBox("Hello kunal")
End Sub
End Class
Public Class rahul
Public Sub New(ByVal x As String)
MsgBox("Hello" & x)
End Sub
Public Sub New(ByVal x As Integer, ByVal y As Integer)
MsgBox(x + y)
End Sub
End Class
End Class

Comments or Responses

Login to post response