How can I create a method that has optional parameters in it in Visual Basic?
+6
A:
Just use the optional keyword and supply a default value. Optional parameters must be the last parameters defined, to avoid creating ambiguous functions.
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
2008-11-19 20:23:47
Didn't realize this was gonna be a 'canned' question. Oh well.
Joel Coehoorn
2008-11-19 20:26:00
It wasn't covered here, so I thought I would add what I found from the Google result.
Steve Duitsman
2008-11-19 20:27:39
+1
A:
Keep in mind....
- All parameters to the right of the first optional parameter must also be optional
- All optional paramters must be assigned a default value
- Default values must be constant expressions (for ex. can't assign string.empty)
Private Sub LogError(byval Message as string, Optional Consume as boolean = False) .... .... end sub
Karl
2009-01-28 12:39:27