From Xojo Documentation

Revision as of 18:55, 9 July 2018 by PLefebvre (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Language Keyword

Used in parameter declarations to indicate that a parameter is optional.


Optional parameter

Part Type Description
parameter Any Data Type Parameter that is optional.


Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.

Sub ExampleMethod(required As Integer, Optional strValue As String, Optional intValue As Integer)
End Sub

// Examples

// Error: if you specify the last optional parameter,
// then you must also specify the one before it
ExampleMethod(3, 4)

// Works: The last parameter is optional
ExampleMethod(3, "test")

// Works: The last parameters are optional

When you use the Optional keyword in a parameter declaration, you make the parameter optional without specifying a default value. The other way of specifying an optional parameter is to give it a default value in the declaration. If you omit the optional parameter when you call such a method, the omitted parameter gets the default value you specified in the declaration.

The Optional keyword precedes the parameter name in the declaration. If the calling statement omits this parameter, it will receive the standard initial value for its type.

Sample Code

If the method declaration is:

myMethod(a As Integer, b As Integer, Optional c As Integer)

If the call omits the optional parameter, it will get the default value of 0.

The other way of making the parameter optional is to give it a default value in the declaration, such as:

myMethod(a As Integer, b As Integer, c As Integer = 10)