Programming Tutorials

Specifying Optional Arguments with default values in Procedures in VB.net

By: Steven Holzner in VB.net 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()
        DisplayMessage()
    End Sub

    Sub DisplayMessage(Optional ByVal strText As String = _
        "Hello from Visual Basic")
        System.Console.WriteLine(strText)
    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
Tip 

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
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)