Use of Constructors and Destructors in VB.NET

This article shows the constructors and destructors in VB.NET.
  • 6313

In this article we will learn about constructor and destructor in VB.NET.

Constructors: Special methods which has following important points.

  1. In VB.NET, this is defined as a Sub with the name of New.

  2. No return type.

  3. It's called whenever an object is created using the New statement.

  4. Can be overloaded.

  5. Can be private.

Destructors: Special methods Which has The following important points.

  1. This is called Finalize in VB.NET.

  2. VB.NET compiler creates a default Finalize method.

  3. Can never be private.

  4. By default is public.

  5. 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.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.