Constructors and Destructors in Visual Basic .NET
In this article, I will explain you how to use of Constructors and Destructors in Visual Basic .NET.
In this article, I will explain you how to use of Constructors and Destructors in Visual Basic .NET.
Constructors
A constructor is a special type of subroutine called at the creation of an object. A constructor method are invoked before an object of it's associated class is created. If a class have a constructor, then the object of that class will be initialized automatically. A constructor looks like an instance method, but it different from a method because it never has an explicit return-type, and can be overridden to provide custom initialization functionality. They have the task of initializing the object's data members. If you combine a constructor that initializes an object to a valid state and property methods that only allow valid states, your objects should remain in a valid state. In Visual Basic we create constructors by adding a Sub procedure named New to a class.
The following code show you the use of constructor in Visual Basic .NET:
Imports System.Console
Module Module1
Sub Main()
Dim con As New Constructor(20)
WriteLine(con.ShowAge())
'storing a value in the constructor by passing a value(20) and calling it with the ShowAge method
Read()
End Sub
End Module
Public Class Constructor
Public Age As Integer
Public Sub New(ByVal x As Integer)
'constructor
Age = x
'storing the value of Age in constructor
End Sub
Public Function ShowAge() As Integer
Return Age
'returning the stored value
End Function
End Class
Destructors
The destructor is the last method run by a class. Destructors in Visual Basic .NET are implemented as a protected method named Finalize. The garbage collector will call your Finalize method if you implement one, but you won't know when that will be you can't invoke this method directly. Finalize method can not overloaded by convention but must be overridden if you are going to introduce your own code in this routine by using Overrides keyword in your declaration. Finalize method invoke automatically when the object is no longer required. The main work of the destructor is release resources and inform other objects that the current objects are going to be destroyed.
The following code show you the use of Destructor in Visual Basic .NET:
Imports System.Console
Module Module1
Sub Main()
Dim obj As New Destroy()
End Sub
End Module
Public Class Destroy
Protected Overrides Sub Finalize()
'creating a Destrustor
Write("VB.NET")
Read()
End Sub
End Class
Summary
Hope this article help you to learn about the use of constructors and destructors Visual Basic .NET.