How can I create a method that has optional parameters in it in Visual Basic?
2 Answers
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)
2 Comments
Joel Coehoorn
Didn't realize this was gonna be a 'canned' question. Oh well.
Steve Duitsman
It wasn't covered here, so I thought I would add what I found from the Google result.
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)