Visual Basic Destructor
Posted by Superadmin on November 15 2022 11:00:08

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.

 

The following are the properties of destructor in a visual basic programming language.

 

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 a visual basic programming language to destruct the unused objects of the 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 the 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.