Variadic Functions in Visual Basic .NET

Variadic functions can be called with any number of trailing arguments. For example, Console.WriteLine is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

Imports System

Module Program
    ' Function to take an arbitrary number of integers as arguments
    Sub Sum(ParamArray nums As Integer())
        Console.Write(String.Join(" ", nums) & " ")
        Dim total As Integer = 0

        ' Iterating over nums array
        For Each num As Integer In nums
            total += num
        Next

        Console.WriteLine(total)
    End Sub

    Sub Main()
        ' Variadic functions can be called with individual arguments
        Sum(1, 2)
        Sum(1, 2, 3)

        ' Applying a slice to a variadic function
        Dim nums As Integer() = {1, 2, 3, 4}
        Sum(nums)
    End Sub
End Module

Within the function, nums is equivalent to an array of Integer. We can call nums.Length, iterate over it with For Each, etc.

Variadic functions can be called in the usual way with individual arguments.

If you already have multiple arguments in an array, apply them to a variadic function using ParamArray like this:

Dim nums As Integer() = {1, 2, 3, 4}
Sum(nums)

To run the program, compile the code and execute it.

$ vbc Program.vb
$ Program.exe
1 2 3
1 2 3 6
1 2 3 4 10

Another key aspect of functions in Visual Basic .NET is their ability to work with arrays and lists, which we’ll look at next.

Next example: Closures.