Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Constructors

Most classes need to perform some sort of initialization whenever a new instance of the class is allocated. The object-oriented way of performing this initialization is to provide a constructor for a class. Whenever a class is instantiated to create a new object, the constructor is called first.

Visual Basic .NET implements constructors by defining a New() subroutine within the class. This subroutine can take arguments just as any other subroutine can; however, defining arguments requires that they be provided whenever the class is instantiated. The following listing shows the New() subroutine from the SmartMsg class:

Public Sub New(ByVal FileName As String)
  'Always call MyBase's New()
  MyBase.New()

  Me.strFileName = FileName

  Read()
End Sub

A constructor in a class that inherits another class should always call the constructor of the base class by calling the MyBase.New() method. Calling this method ensures that any initialization of the base class is performed when necessary.

In the SmartMsg class, the constructor assigns the FileName argument to the strFileName member and calls the Read() subroutine for further initialization.

The constructor isn't always a requirement in Visual Basic .NET class definitions, and you might have a class without a New() method. However, providing a constructor for a class is generally good practice even if it's not required.

A class can also define multiple constructors. It could have a constructor that takes no parameters and then have constructors that take various parameters to initialize the class at the time it's constructed. For example, the String class in the .NET Framework defines three additional constructors besides the default provided by the Object class. They are declared as follows:

Public Sub New(Char())
Public Sub New(Char, Integer)
Public Sub New(Char(), Integer, Integer)

Each of these constructors initializes the new String object differently. How the new object is instantiated and what parameters are provided, if any, determine which constructor is used.

  • + Share This
  • 🔖 Save To Your Account