次の方法で共有


Optional (Visual Basic)

Specifies that a procedure argument can be omitted when the procedure is called.

Remarks

For each optional parameter, you must specify a constant expression as the default value of that parameter. If the expression evaluates to Nothing, the default value of the value data type is used as the default value of the parameter.

If the parameter list contains an optional parameter, every parameter that follows it must also be optional.

The Optional modifier can be used in these contexts:

Note

When calling a procedure with or without optional parameters, you can pass arguments by position or by name. For more information, see Passing Arguments by Position and by Name (Visual Basic).

Note

You can also define a procedure with optional parameters by using overloading. If you have one optional parameter, you can define two overloaded versions of the procedure, one that accepts the parameter and one that doesn’t. For more information, see Procedure Overloading (Visual Basic).

Example

The following example defines a procedure that has an optional parameter.

Public Function FindMatches(ByRef values As List(Of String),
                            ByVal searchString As String,
                            Optional ByVal matchCase As Boolean = False) As List(Of String)

    Dim results As IEnumerable(Of String)

    If matchCase Then
        results = From v In values
                  Where v.Contains(searchString)
    Else
        results = From v In values
                  Where UCase(v).Contains(UCase(searchString))
    End If

    Return results.ToList()
End Function

The following example demonstrates how to call a procedure with arguments passed by position and with arguments passed by name. The procedure has two optional parameters.

Private Sub TestParameters()
    ' Call the procedure with its arguments passed by position,
    studentInfo("Mary", 19, #9/21/1981#)

    ' Omit one optional argument by holding its place with a comma.
    studentInfo("Mary", , #9/21/1981#)

    ' Call the procedure with its arguments passed by name.
    studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")

    ' Supply an argument by position and an argument by name.
    studentInfo("Mary", birth:=#9/21/1981#)
End Sub 

Private Sub studentInfo(ByVal name As String,
   Optional ByVal age As Short = 0,
   Optional ByVal birth As Date = #1/1/2000#)

    Console.WriteLine("name: " & name)
    Console.WriteLine("age: " & age)
    Console.WriteLine("birth date: " & birth)
    Console.WriteLine()
End Sub

See Also

Reference

Parameter List (Visual Basic)

Concepts

Optional Parameters (Visual Basic)

Other Resources

Keywords (Visual Basic)