How to: Define Optional Parameters for a Procedure (Visual Basic)

You can specify that a procedure parameter is optional, so that the calling code does not have to supply an argument for it when it calls the procedure. When you do this, you define a default value that the procedure uses if the argument is not supplied.

You can define more than one optional parameter, but all the optional parameters must be at the end of the parameter list. All the required parameters must precede every optional parameter.

To define an optional parameter

  1. In the procedure declaration, precede the parameter name in the parameter list with the Optional keyword.

  2. Follow the parameter name with an As clause as usual, and follow the As clause with an equal sign (=).

  3. Follow the equal sign with the default value for the parameter. This must be a constant expression, so that the compiler can completely evaluate it at compile time.

  4. You must declare every subsequent parameter as Optional.

Example

The following example shows a procedure declaration with an optional parameter.

Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
    If office = "QJZ" Then
        Debug.WriteLine("office not supplied -- using Headquarters")
        office = "Headquarters"
    End If
    ' Insert code to notify headquarters or specified office.
End Sub

If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".

Compiling the Code

You must specify a default value for every optional parameter in the procedure declaration. Be sure that each default value is a constant that the compiler can evaluate at compile time.

See Also

Tasks

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

How to: Determine Whether an Optional Parameter Was Supplied (Visual Basic)

Reference

Optional (Visual Basic)

ParamArray (Visual Basic)

Concepts

Procedure Parameters and Arguments (Visual Basic)

Passing Arguments by Value and by Reference (Visual Basic)

Passing Arguments by Position and by Name (Visual Basic)

Optional Parameters (Visual Basic)

Parameter Arrays (Visual Basic)

Procedure Overloading (Visual Basic)