views:

1012

answers:

2

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
Didn't realize this was gonna be a 'canned' question. Oh well.
Joel Coehoorn
It wasn't covered here, so I thought I would add what I found from the Google result.
Steve Duitsman
+1  A: 

Keep in mind....

  1. All parameters to the right of the first optional parameter must also be optional
  2. All optional paramters must be assigned a default value
  3. 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 - http://designlunacy.blogspot.com/

Karl