Closures in Visual Basic .NET

Visual Basic .NET supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

Imports System

Module Closures
    ' This function IntSeq returns another function, which
    ' we define anonymously in the body of IntSeq. The
    ' returned function closes over the variable i to
    ' form a closure.
    Function IntSeq() As Func(Of Integer)
        Dim i As Integer = 0
        Return Function()
                   i += 1
                   Return i
               End Function
    End Function

    Sub Main()
        ' We call IntSeq, assigning the result (a function)
        ' to nextInt. This function value captures its
        ' own i value, which will be updated each time
        ' we call nextInt.
        Dim nextInt As Func(Of Integer) = IntSeq()

        ' See the effect of the closure by calling nextInt
        ' a few times.
        Console.WriteLine(nextInt())
        Console.WriteLine(nextInt())
        Console.WriteLine(nextInt())

        ' To confirm that the state is unique to that
        ' particular function, create and test a new one.
        Dim newInts As Func(Of Integer) = IntSeq()
        Console.WriteLine(newInts())
    End Sub
End Module

To run the program, save it as Closures.vb and compile it using the Visual Basic compiler:

$ vbc Closures.vb
$ mono Closures.exe
1
2
3
1

In this Visual Basic .NET example, we’ve created a closure using an anonymous function. The IntSeq function returns another function that increments and returns a counter. Each time we call IntSeq, we get a new function with its own separate counter.

The Func(Of Integer) type represents a function that takes no parameters and returns an Integer. This is equivalent to the func() int type in the original example.

The Main subroutine demonstrates how to use these closures. We create two separate counters, nextInt and newInts, showing that each maintains its own state.

Visual Basic .NET’s lambda expressions (anonymous functions) and closures work similarly to those in other languages, allowing for powerful and flexible programming patterns.

The next feature of functions we’ll look at is recursion.