Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB.NET
Expertise: beginner
Nov 24, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 If
End Sub
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date