Optional Examples, Named Arguments
This page was last reviewed on Feb 10, 2022.
Dot Net Perls
Optional. A Sub receives arguments. Sometimes a default value makes sense for a parameter. With Optional, we can specify a default value and then omit it when calling a method.
A syntax change. Optional arguments are a syntax improvement. The VB.NET compiler inserts the default values for an Optional argument in all calling locations.
Optional example. Let us begin with this simple example. The "name" argument here is Optional. Its default value, specified with an assignment expression, is the string "Empty."
Thus When called with no argument, the name argument is automatically assigned to "Empty" for us.
However When an argument is specified, the "Empty" value is not used. It is a default value only.
Module Module1 Sub PrintName(ByVal Optional name As String = "Empty") ' The "name" argument will have a default value if no new as specified. Console.WriteLine(name) End Sub Sub Main() ' Specify no argument. PrintName() ' Specify arguments. PrintName("Cat") PrintName("Dog") End Sub End Module
Empty Cat Dog
Named arguments. In VB.NET we find named argument syntax. Here we combine Optional arguments and named arguments. The compiler resolves all this syntax.
Tip We can mix regular argument usage (which is order-based) with named arguments. But Optional arguments must come at the end.
Detail We use String interpolation syntax in the Console.WriteLine call. The name and size values are written.
Module Module1 Sub Print(ByVal Optional name As String = "Empty", ByVal Optional size As Integer = 0) ' Use string interpolation to print name and size arguments. Console.WriteLine($"{name} {size}") End Sub Sub Main() ' Specify both arguments in order. Print("Cat", 2) ' Use 1 named argument. Print(name:="Bird") ' Use 1 named argument at last position. Print("Dog", size:=10) ' Use 2 named arguments. Print(size:=100, name:="Horse") End Sub End Module
Cat 2 Bird 0 Dog 10 Horse 100
Some notes. We can add Optional keywords to all our methods. But this rapidly becomes confusing. Instead, using Optional only on some parameters on often-called methods is a good approach.
A review. Optional and named arguments are syntax improvements to the VB.NET language. They simplify things when used correctly. Programmer skill is essential to using them well.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 10, 2022 (edit link).
© 2007-2024 Sam Allen.