54

How can I create a method that has optional parameters in it in Visual Basic?

2 Answers 2

106

Use the Optional keyword and supply a default value. Optional parameters must be the last parameters defined, to avoid creating ambiguous function signatures.

Sub MyMethod(ByVal Param1 As String, Optional ByVal FlagArgument As Boolean = True)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If

End Sub

Call it like this:

MyMethod("test1")

Or like this:

MyMethod("test2", False)
Sign up to request clarification or add additional context in comments.

2 Comments

Didn't realize this was gonna be a 'canned' question. Oh well.
It wasn't covered here, so I thought I would add what I found from the Google result.
4

Bear in mind that the Optional parameter cannot be before a required argument.

Otherwise, the code below will produce an error:

Sub ErrMethod(Optional ByVal FlagArgument As Boolean = True, ByVal Param1 As String)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If
End Sub

Even though it is a common error...it is not very well explained by the debugger.

It does make sense though if you think about it, imagine this call:

ErrMethod(???, Param1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.