hi friends
What are the constructor and destructor? please explain with examples..
Thanks...
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Satyapriya NayakRank #47 · 31.5K reputationPosted Aug 25, 2011, 6:14 AM EDT
Below i explain constructor and destructor with examples.
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
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
Destructor release the memory of the object created by the constructor. It is of two types dispose and finalize .In dispose we have to intentionally call dispose destructor. But in finalize it is called automatically when the last reference of the object is released
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.dispose()
End Sub
Public Class raj
Public Sub New()
MsgBox("Instant constructor of raj")
End Sub
Shared Sub New()
MsgBox("Shared constructor of raj")
End Sub
Public Overloads Sub dispose()
MsgBox("Dispose destructor of raj")
End Sub
Protected Overrides Sub finalize()
MsgBox("Finalize destructor of raj")
End Sub
End Class
End Class
Thanks
If this post helps you mark it as answer