METHOD OVERLOADING

Visual Basic .NET enables you to give a class more than one method with the same name but with different parameters. The program decides which version of the method to use based on the parameters being passed to the method.

For example, the Person class shown in the following code has two constructors named New. The first takes no parameters and initializes the object’s FirstName and LastName variables to default values. The second overloaded constructor takes two strings as parameters and uses them to initialize FirstName and LastName.

Public Class Person
    Public FirstName As String
    Public LastName As String
 
    Public Sub New()
        FirstName = "<first>"
        LastName = "<last>"
    End Sub
 
    Public Sub New(first_name As String, last_name As String)
        FirstName = first_name
        LastName = last_name
    End Sub
End Class

The following code uses these constructors. The first statement passes no parameters to the constructor, so Visual Basic uses the first version of the New method. The second statement passes two strings to the constructor, so Visual Basic uses the second constructor.

Dim person1 As New Person()
Dim person2 As New Person("Rod", "Stephens")

A common technique for providing constructors that take different numbers of arguments is to make the simpler constructors call those with more parameters passing them default values. In the following code, the parameterless constructor calls a constructor that takes two parameters:

Public Class Person Public FirstName As String Public LastName ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.