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 As String
Public Sub New()
Me.New("<first>", "<last>")
End Sub
Public Sub New(first_name As String, last_name As String)
FirstName = first_name
LastName = last_name
End Sub
End Class
Two overloaded methods cannot differ only by optional parameters. For example, the first_name and last_name parameters in the previous constructor could not both be optional. If they were, Visual Basic .NET could not tell which version of the New subroutine to call if the program passed it no parameters. Although you cannot make the parameters optional in the second constructor, you can get a similar result by combining the two constructors, as shown in the following code:
Public Class Person
Public FirstName As String
Public LastName As String
Public Sub New(
Optional first_name As String = "<first>",
Optional last_name As String = "<last>")
FirstName = first_name
LastName = last_name
End Sub
End Class
Overloaded functions also cannot differ only in their return types. In other words, you cannot have two versions of a function with the same name and parameters but different return types.