Procedure Overloading - Visual Basic (original) (raw)

Overloading a procedure means defining it in multiple versions, using the same name but different parameter lists. The purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by name. You do this by varying the parameter list.

Overloading Rules

When you overload a procedure, the following rules apply:

Multiple Versions of a Procedure

Suppose you are writing a Sub procedure to post a transaction against a customer's balance, and you want to be able to refer to the customer either by name or by account number. To accommodate this, you can define two different Sub procedures, as in the following example:

Sub postName(ByVal custName As String, ByVal amount As Single)
    ' Insert code to access customer record by customer name.
End Sub
Sub postAcct(ByVal custAcct As Integer, ByVal amount As Single)
    ' Insert code to access customer record by account number.
End Sub

Overloaded Versions

An alternative is to overload a single procedure name. You can use the Overloads keyword to define a version of the procedure for each parameter list, as follows:

Overloads Sub post(ByVal custName As String, ByVal amount As Single)
    ' Insert code to access customer record by customer name.
End Sub
Overloads Sub post(ByVal custAcct As Integer, ByVal amount As Single)
    ' Insert code to access customer record by account number.
End Sub

Additional Overloads

If you also wanted to accept a transaction amount in either Decimal or Single, you could further overload post to allow for this variation. If you did this to each of the overloads in the preceding example, you would have four Sub procedures, all with the same name but with four different signatures.

Advantages of Overloading

The advantage of overloading a procedure is in the flexibility of the call. To use the post procedure declared in the preceding example, the calling code can obtain the customer identification as either a String or an Integer, and then call the same procedure in either case. The following example illustrates this:

Imports MSVB = Microsoft.VisualBasic
Dim customer As String
Dim accountNum As Integer
Dim amount As Single
customer = MSVB.Interaction.InputBox("Enter customer name or number")
amount = MSVB.Interaction.InputBox("Enter transaction amount")
Try
    accountNum = CInt(customer)
    Call post(accountNum, amount)
Catch
    Call post(customer, amount)
End Try

See also