How to: Define a Parameter for a Procedure - Visual Basic (original) (raw)
If the parameter is optional, precede the passing mechanism with Optional and follow the parameter data type with an equal sign (=
) and a default value.
The following example defines the outline of a Sub
procedure with three parameters. The first two are required and the third is optional. The parameter declarations are separated in the parameter list by commas.
Sub updateCustomer(ByRef c As customer, ByVal region As String,
Optional ByVal level As Integer = 0)
' Insert code to update a customer object.
End Sub
The first parameter accepts a customer
object, and updateCustomer
can directly update the variable passed to c
because the argument is passed ByRef. The procedure cannot change the values of the last two arguments because they are passed ByVal.
If the calling code does not supply a value for the level
parameter, Visual Basic sets it to the default value of 0.
If the type checking switch (Option Strict Statement) is Off
, the As
clause is optional when you define a parameter. However, if any one parameter uses an As
clause, all of them must use it. If the type checking switch is On
, the As
clause is required for every parameter definition.
Specifying data types for all your programming elements is known as strong typing. When you set Option Strict On
, Visual Basic enforces strong typing. This is strongly recommended, for the following reasons:
- It enables IntelliSense support for your variables and parameters. This allows you to see their properties and other members as you type in your code.
- It allows the compiler to perform type checking. This helps catch statements that can fail at run time due to errors such as overflow. It also catches calls to methods on objects that do not support them.
- It results in faster execution of your code. One reason for this is that if you do not specify a data type for a programming element, the Visual Basic compiler assigns it the
Object
type. Your compiled code might have to convert back and forth betweenObject
and other data types, which reduces performance.