Use of Constructors and Destructors in VB.NET
This article shows the constructors and destructors in VB.NET.
In this article we will learn about constructor and destructor in VB.NET.
Constructors: Special methods which has following important points.
-
In VB.NET, this is defined as a Sub with the name of New.
-
No return type.
-
It's called whenever an object is created using the New statement.
-
Can be overloaded.
-
Can be private.
Destructors: Special methods Which has The following important points.
-
This is called Finalize in VB.NET.
-
VB.NET compiler creates a default Finalize method.
-
Can never be private.
-
By default is public.
-
Called automatically when an object releases it memory.
Code define both constructor and destructor in c#:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConstDestructor
{
class MyClass
{
private MyClass() { }
}
class Numeric
{
int a, b;
public Numeric(int a, int b)
{
this.a = a;
this.b = b;
}
public Numeric(int a)
: this(a, 0)
{
}
public Numeric()
: this(0)
{
}
~Numeric()
{
}
static void Main(string[] args)
{
Numeric num = new Numeric();
}
}
}
Code define both constructor and destructor in Visual Basic:
Module module1
Class [MyClass]
Private Sub New() ' define the constructor
End Sub
End Class
Class Numeric
Private a As Integer, b As Integer
Public Sub New(ByVal a As Integer, ByVal b As Integer)
Me.a = a
Me.b = b
End Sub
Public Sub New(ByVal a As Integer)
Me.New(a, 0)
End Sub
Public Sub New()
Me.New(0)
End Sub
Protected Overrides Sub Finalize()
Try
Finally
MyBase.Finalize() 'define the destructor
End Try
End Sub
Public Shared Sub Main(ByVal args As String())
Dim num As New Numeric()
End Sub
End Class
End Module
The above code define the constructor and destructor in c# and VB.NET.