- Sub Procedures
- Creating Functions
- Using Optional Arguments
- Passing a Variable Number of Arguments
- Preserving Data Between Procedure Calls
- Understanding Scope
- Handling Runtime Errors
- Unstructured Exception Handling
- Structured Exception Handling
- Introducing Classes and Objects
- Summary
- Q&A
- Workshop
Using Optional Arguments
You can make some arguments in a procedure call optional, which means that if the calling code doesn't specify a value for them, a default value will be used. To make an argument optional, you use the Optional keyword and supply a default value like this, where the strText argument of the ShowMessage function is optional and the default value is "Hello there!":
Module Module1 Sub Main() End Sub Sub ShowMessage(Optional ByVal strText As String = "Hello there!") Console.WriteLine(strText) End Sub End Module
Now if you call ShowMessage with no arguments, as shown in Listing 3.3 and the Optional project in the code for this book, the message "Hello there!" will be displayed.
Listing 3.3 Using Optional Arguments (Optional project, Module1.vb)
Module Module1 Sub Main() ShowMessage() Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(Optional ByVal strText As String = "Hello there!") Console.WriteLine(strText) End Sub End Module
Note that if you declare one argument optional in a procedure's argument list, all following arguments must be optional too (otherwise, Visual Basic wouldn't know which argument had been omitted).