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.
Optional
arguments are a syntax improvement. The VB.NET compiler inserts the default values for an Optional
argument in all calling locations.
Optional
exampleLet us begin with this simple example. The "name" argument here is Optional
. Its default value, specified with an assignment expression, is the string
"Empty."
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 ModuleEmpty Cat Dog
In VB.NET we find named argument syntax. Here we combine Optional
arguments and named arguments. The compiler resolves all this syntax.
Optional
arguments must come at the end.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 ModuleCat 2 Bird 0 Dog 10 Horse 100
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.
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.