typestar

Optional and named arguments in Visual Basic

Defaults, sugar:=True call sites and ParamArray catch-alls.

Console.WriteLine(Brew(2))
Console.WriteLine(Brew(1, "strong"))
Console.WriteLine(Brew(3, sugar:=True))
Console.WriteLine(Total(4, 8, 15, 16, 23, 42))

Function Brew(cups As Integer,
              Optional strength As String = "medium",
              Optional sugar As Boolean = False) As String
    Dim extra = If(sugar, " with sugar", "")
    Return $"{cups} cups, {strength}{extra}"
End Function

Function Total(ParamArray values() As Integer) As Integer
    Return values.Sum()
End Function

How it works

  1. Optional ... = "medium" gives the parameter a default.
  2. sugar:=True names the argument so the middle default stands.
  3. ParamArray collects any number of arguments into an array.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
454
Tokens
123
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 2 of 3 in Subs & functions, step 14 of 29 in Language basics.

← Previous Next →