Recursion in Visual Basic .NET

Our first example demonstrates recursion. Here’s the full source code:

Imports System

Module RecursionExample
    ' This Fact function calls itself until it reaches the
    ' base case of Fact(0).
    Function Fact(n As Integer) As Integer
        If n = 0 Then
            Return 1
        End If
        Return n * Fact(n - 1)
    End Function

    Sub Main()
        Console.WriteLine(Fact(7))

        ' In VB.NET, we can define local functions inside methods,
        ' which can be recursive. This is similar to the closure
        ' concept in some other languages.
        Dim Fib As Func(Of Integer, Integer)
        Fib = Function(n As Integer) As Integer
                  If n < 2 Then
                      Return n
                  End If
                  ' Since Fib was previously declared, VB.NET
                  ' knows which function to call with Fib here.
                  Return Fib(n - 1) + Fib(n - 2)
              End Function

        Console.WriteLine(Fib(7))
    End Sub
End Module

To run the program, save it as RecursionExample.vb and use the VB.NET compiler:

$ vbc RecursionExample.vb
$ mono RecursionExample.exe
5040
13

This example demonstrates two types of recursive functions in VB.NET:

  1. A standard recursive function (Fact) that calculates the factorial of a number.
  2. A local function (Fib) defined inside the Main method, which calculates Fibonacci numbers recursively.

The Fact function is a classic example of recursion, calling itself with a smaller argument until it reaches the base case.

The Fib function is defined as a local function within Main. This is similar to the concept of closures in some other languages. In VB.NET, local functions can be recursive and can capture variables from the enclosing scope.

Both functions are called with the argument 7, and their results are printed to the console.