C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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.
ConsoleVB.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