affiliate_link

Thursday, October 2, 2008

Constructor and Destructor

Contructor
A constructor is a special kind of a method that is called whenever a class is initialized

VB.Net code snippet
    Public Sub New()
' Perform initialization
Debug.WriteLine("I am alive")
End Sub
Data can be passed to a constructor for more flexibility and power. Constructors with parameters are called parameterized constructors.

Destructor
Desctructor is a method that is called to cleanup resources.

Visual Basic .NET provides a Finalize destructor. This destructor is called when the .NET garbage collector determines that the object is no longer needed. There may be a delay between the time an object is terminated and the time the garbage collector actually destroys the object.

Tip
You should not normally use a Finalize destructor because of this delay and the additional processing required by the system to manage objects with a Finalize destructor. Use the Dispose destructor instead.

In order to better manage the resources used by your class, implement the IDisposable interface and the Dispose destructor:

VB.Net code snippet

    Implements IDisposable
Public Sub Dispose() Implements System.IDisposable.Dispose
' Perform termination
End Sub
This destructor is not called automatically, so it must be explicitly called as shown in the next section.

Tip The Dispose destructor is not required, but it is recommended. By implementing the Dispose destructor in every class, even if it does not do anything, developers can routinely call the Dispose method on any object.
   m_oCustomer.Dispose()
m_oCustomer = Nothing

No comments: