How can I create a method that has optional parameters in it in Visual Basic?
Asked
Active
Viewed 8.5k times
2 Answers
96
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)

Joel Coehoorn
- 399,467
- 113
- 570
- 794
-
1Didn't realize this was gonna be a 'canned' question. Oh well. – Joel Coehoorn Nov 19 '08 at 20:26
-
1It wasn't covered here, so I thought I would add what I found from the Google result. – Steve Duitsman Nov 19 '08 at 20:27
1
Have in mind that optional argument cannot have place before a required argument.
This code will show 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
It is common error, no much explained by debugger... It have sense, imagine the call...
ErrMethod(???, Param1)

Marcelo Nuñez
- 31
- 2