Visual Basic Destructor

In visual basic, Destructor is a special method of a class and it is useful in class to destroy the object or instances of classes. The destructor in visual basic will invoke automatically whenever the class instances become unreachable.

 

Following are the properties of destructor in visual basic programming language.

 

  • In visual basic, destructors can be used only in classes and a class can contain only one destructor.
  • The destructor in class can be represented by using Finalize() method.
  • The destructor in visual basic won’t accept any parameters and access modifiers.
  • The destructor will invoke automatically, whenever an instance of class is no longer needed.
  • The destructor automatically invoked by garbage collector whenever the class objects that are no longer needed in application.

Visual Basic Destructor Syntax

Following is the syntax of defining the destructor in visual basic programming language.

 

Class User

    ' Destructor

    Protected Overrides Sub Finalize()

        ' Your Code

    End Sub

End Class

If you observe the above syntax, we created a destructor using Finalize() method.

Visual Basic Destructor Example

Following is the example of using destructor in visual basic programming language to destruct the unused objects of class.

 

Module Module1

    Class User

        Public Sub New()

            Console.WriteLine("An Instance of class created")

        End Sub

        Protected Overrides Sub Finalize()

            Console.WriteLine("An Instance of class destroyed")

        End Sub

    End Class

    Sub Main()

        Details()

        GC.Collect()

        Console.ReadLine()

    End Sub

    Public Sub Details()

        Dim user As User = New User()

    End Sub

End Module

If you observe above example, we created a class with default constructor and destructor. Here, we created an instance of class “User” in Details() method and whenever the Details function execution is done, then the garbage collector (GC) automatically will invoke the destructor in User class to clear the object of class.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Destructor Example Result

 

This is how we can use the destructor in visual basic programming language to clear or destruct the unused objects based on our requirements.

Topics Covered