Programming Tutorials

Specifying Optional Arguments with default values in Procedures in

By: Steven Holzner in Tutorials on 2010-11-17  

You also can make arguments optional in VB .NET procedures if you use the Optional keyword when declaring those arguments. Note that if you make one argument optional, all the following arguments must also be optional, and you have to specify a default value for each optional argument (although you can set them to the keyword Nothing if you wish). You specify a default value with = default_value in the procedure's argument list. Here's an example where I'm making the string argument you pass to a Sub procedure named DisplayMessage optional, and giving that argument the default value "Hello from Visual Basic":

Module Module1
    Sub Main()
    End Sub

    Sub DisplayMessage(Optional ByVal strText As String = _
        "Hello from Visual Basic")
    End Sub
End Module

Now when I call DisplayMessage with no arguments, as in the code above, the default value is used and this code displays:

Hello from Visual Basic

VB6 had a function named IsMissing that would test if an optional argument had been given a value or not, but now that all optional arguments have default values, IsMissing has been removed. You can, however, use the IsNothing function to check if an argument has been set to Nothing.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in )

Latest Articles (in