Providing a default value for optional arguments

Unlike VB6, VB.NET requires that you specify the default value of any Optional argument. In general you should use a value that is invalid under normal circumstances, so that the called procedure can discern whether the argument has been actually passed or not. For example, you should use -1 as a special value if the argument shouldn’t take negative values; or you can use the largest negative or positive number for that numeric type. In the latter case, you might use the MinValue and MaxValue properties that all numeric classes expose:

Sub MyProc(Optional ByVal X As Long = Long.MinValue)    If X = Long.MinValue Then        ' The X argument has been omitted (presumably).        Console.WriteLine(X)  ' => -9223372036854775808    End If    ' ....End Sub

If the optional argument is a Single or Double, you can also use the special NaN (Not-a-Number) value for its default:

Sub MyProc(Optional ByVal X As Double = Double.NaN)    If Double.IsNaN(x) Then        ' The X argument has been omitted.    End IfEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: