typestar

Lambdas in Visual Basic

Function() and Sub() expressions, one line or a full block.

Dim twice = Function(n As Integer) n * 2
Console.WriteLine(twice(21))

Dim shout As Action(Of String) = Sub(s) Console.WriteLine(s.ToUpper())
shout("done")

Dim describe = Function(n As Integer)
                   If n Mod 2 = 0 Then Return $"{n} is even"
                   Return $"{n} is odd"
               End Function

For Each n In {7, 12}
    Console.WriteLine(describe(n))
Next

How it works

  1. Function(n As Integer) n * 2 returns its expression.
  2. A Sub lambda fits an Action slot — statements, no value.
  3. Multi-line lambdas open a block and close with End Function.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
329
Tokens
97
Three-star pace
80 tpm

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

Type this snippet

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

← Previous Next →

Lambdas in other languages