HomeSearch

VB.NET Optional String, Integer: Named Arguments

Use the Optional keyword to specify a default value for an argument. Learn the syntax for named arguments.

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.Keywords

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.

VB.NET program that uses Optional argument 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 Output 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.

WriteLine: We use String interpolation syntax in the Console.WriteLine call. The name and size values are written.

Console
VB.NET program that uses named arguments 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 Output 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.