Dela via


How to: Define Multiple Versions of a Procedure (Visual Basic)

You can define a procedure in multiple versions by overloading it, using the same name but a different parameter list for each version. The purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by name.

For more information, see Procedure Overloading (Visual Basic).

To define multiple versions of a procedure

  1. Write a Sub or Function declaration statement for each version of the procedure you want to define. Use the same procedure name in every declaration.

  2. Precede the Sub or Function keyword in each declaration with the Overloads (Visual Basic) keyword. You can optionally omit Overloads in the declarations, but if you include it in any of the declarations, you must include it in every declaration.

  3. Following each declaration statement, write procedure code to handle the specific case where the calling code supplies arguments matching that version's parameter list. You do not have to test for which parameters the calling code has supplied. Visual Basic passes control to the matching version of your procedure.

  4. Terminate each version of the procedure with the End Sub or End Function statement as appropriate.

Example

The following example defines a Sub procedure to post a transaction against a customer's balance. It uses the Overloads keyword to define two versions of the procedure, one that accepts the customer by name and the other by account number.

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

The calling code can obtain the customer identification as either a String or an Integer, and then use the same calling statement in either case.

For information on how to call these versions of the post procedure, see How to: Call an Overloaded Procedure (Visual Basic).

Compiling the Code

Make sure each of your overloaded versions has the same procedure name but a different parameter list.

See Also

Tasks

Troubleshooting Procedures (Visual Basic)

How to: Overload a Procedure that Takes Optional Parameters (Visual Basic)

How to: Overload a Procedure that Takes an Indefinite Number of Parameters (Visual Basic)

Concepts

Procedures in Visual Basic

Procedure Parameters and Arguments (Visual Basic)

Considerations in Overloading Procedures (Visual Basic)

Overload Resolution (Visual Basic)