51

How can I create a method that has optional parameters in it in Visual Basic?

pythonian29033
  • 5,148
  • 5
  • 31
  • 56
Steve Duitsman
  • 2,749
  • 5
  • 27
  • 39

2 Answers2

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
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)