Reputation: 2791
How can I create a method that has optional parameters in it in Visual Basic?
Upvotes: 54
Views: 94486
Reputation: 61
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)
Upvotes: 4
Reputation: 415600
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)
Upvotes: 105