Friday, May 2, 2008

Constructors in VB.NET

Constructors in VB.NET:::

A constructor is a special member function whose task is to initialize the objects of it's class. This is the first method that is run when an instance of a type is created. A constructor is invoked whenever an object of it's associated class is created. If a class contains a constructor, then an object created by that class will be initialized automatically. We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object. Constructors can never return a value, and can be overridden to provide custom intitialization functionality. In Visual Basic we create constructors by adding a Sub procedure named New to a class. The following code demonstrates the use of constructors in Visual Basic.

Module Module1

Sub Main()

Dim con As New Constructor(10)
WriteLine(con.display())
'storing a value in the constructor by passing a value(10) and calling it with the
'display method
Read()

End Sub

End Module

Public Class Constructor
Public x As Integer

Public Sub New(ByVal value As Integer)
'constructor
x = value
'storing the value of x in constructor
End Sub

Public Function display() As Integer
Return x
'returning the stored value
End Function

End Class


Destructors

A destructor, also know as finalizer, is the last method run by a class. Within a destructor we can place code to clean up the object after it is used, which might include decrementing counters or releasing resources. We use Finalize method in Visual Basic for this and the Finalize method is called automatically when the .NET runtime determines that the object is no longer required. When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class. We normally use Finalize method to deallocate resources and inform other objects that the current object is going to be destroyed. Because of the nondeterministic nature of garbage collection, it is very hard to determine when a class's destructor will be called. The following code demonstrates the use of Finalize method.

Module Module1

Sub Main()
Dim obj As New Destructor()
End Sub

End Module

Public Class Destructor

Protected Overrides Sub Finalize()
Write("hello")
Read()
End Sub

End Class


When you run the above code, the word and object, obj of class, destructor is created and "Hello" is displayed. When you close the DOS window, obj is destroyed.

No comments: