Constructor initialization in vb.net

Constructors are special methods that are automatically called when creating Objects. We know that we have to initialize objects before using them. There are two ways to initialize members of a class (objects) using constructors.

1.By passing arguments to a constructor, we can initialize member variables as shown below.


Public Class Account
    Private mCode As String         		 	'Account code
    Private mName As String          			'Account Name
    Private mdescription As String   			'Account description
    Protected mBalance As Double       			'Account Balance


The below code is an example of an overloaded constructor with arguments.

    Public Sub New(ByVal code, ByVal name, ByVal description, ByVal balance)
        mCode = code
        mName = name
        mdescription = description
        mBalance = balance
    End Sub

The below code is an example of an overloaded constructor without arguments. 

    Public Sub New()

    End Sub
End Class



2. We can also initialize member variables with default values inside the constructor as shown below.

Vb 2008
Sub New()
        mCode ="A001"
        mName = "Account1"
        mdescription ="Default Account" 
        mBalance = 0.0
End Sub
C# 2008
Public Account()
{
        mCode ="A001";
        mName = "Account1";
        mdescription ="Default Account" ;
        mBalance = 0.0;
}


How to initialize Base class Object from inside Derived Class constructor

To access members of the base class, firstly we have to run the base class constructors in the derived class' constructor. This ensures that all the objects are in an initialized state. When we need to access the functionality of a class which is in a inheritance hierarchy, the constructors are executed beginning with the highest base class to the lowest class. In vb.net , the 'MyBase' keyword is used to access any of the base class members.

In the code given below, we use MyBase keyword to call the constructor of the base class - 'Account' class.

Creating a constructor in derived class without parameters is shown below.

    Public Sub New()
        MyBase.New()
    End Sub


Creating a constructor in derived class with parameters is shown below.

Public Sub New(ByVal code, ByVal name, ByVal description, ByVal balance, ByVal address, ByVal phone)
        MyBase.New(code, name, description, balance)
        mAddress = address
        mPhone = phone
    End Sub