Functions in Visual Basic .NET

Functions are central in Visual Basic .NET. We’ll learn about functions with a few different examples.

Imports System

Module Program
    ' Here's a function that takes two Integers and returns
    ' their sum as an Integer.
    Function Plus(a As Integer, b As Integer) As Integer
        ' Visual Basic .NET doesn't require explicit returns,
        ' the value of the last expression is automatically returned.
        Return a + b
    End Function

    ' When you have multiple consecutive parameters of
    ' the same type, you can declare them together.
    Function PlusPlus(a As Integer, b As Integer, c As Integer) As Integer
        Return a + b + c
    End Function

    Sub Main()
        ' Call a function just as you'd expect, with
        ' name(args).
        Dim res As Integer = Plus(1, 2)
        Console.WriteLine("1+2 = " & res)

        res = PlusPlus(1, 2, 3)
        Console.WriteLine("1+2+3 = " & res)
    End Sub
End Module

To run the program, save it as Functions.vb and use the Visual Basic .NET compiler:

$ vbc Functions.vb
$ mono Functions.exe
1+2 = 3
1+2+3 = 6

There are several other features to Visual Basic .NET functions. One is multiple return values, which we can achieve using tuples or custom objects.