Constructors and Destructors in VB.NET

Introduction to Constructors and Destructors in VB.NET

Explanation

Constructors and Destructors in VB.NET

Constructors used in a class are member functions to initialize or set the objects of a class in VB.net. They dont return any value and are defined in a Sub with a keyword New.
Multiple constructors can be created in class with any access specifiers, by default constructors are of Public access type.
Example:

Module Module1
Public Class Sample
Private a As Integer
Public Sub New(ByVal setval As Integer)
a = setval
End Sub
Public Function disp()
Return a
End Function
End Class
Sub Main()
Dim d As New Sample(5)
Console.WriteLine("Value of a is initialized to:")
Console.WriteLine(d.disp())
Console.Read()
End Sub
End Module
Result:

Value of a is initialized to:
5
Description:

In the above example, using the Constructor declared within the sub procedure New the value of a is set to 5.
Destructors:

Destructors or finalizer is a method used to deallocate the resources of an object that are no longer used, its invoked automatically by the VB.net environment. The keyword Overrides is used with the Finalizer method.
Example:

Protected Overrides Sub Finalize()
Console.WriteLine("Calling Destructor")
Ens Sub

Visual Basic Tutorial


Ask Questions

Ask Question