Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Control Flow and Procedures

Subs and Functions

Write reusable procedures in Visual Basic .NET: Sub versus Function, Return, ByVal and ByRef, Optional and named arguments, overloading, recursion, lambdas and scope, with examples and common mistakes.

A procedure is a named block of code you can run from many places. Procedures remove repetition, give ideas names and let you test pieces separately. VB.NET has two kinds: a Sub does something and returns nothing; a Function computes and returns a value. This lesson covers declaring them, passing arguments in different ways, overloading, recursion and lambdas. Listings are VB.NET (read-only) with runnable C# stand-ins.

Sub: do something

VB
Sub Greet(name As String)
    Console.WriteLine($"Hello, {name}!")
End Sub

Greet("Ada")          ' call: parentheses are required in modern VB

A Sub can have any number of parameters and ends at End Sub or at Return (with no value). To call it from another place just write its name. Older code used Call Greet("Ada"), which is no longer needed.

Function: compute a value

A Function declares its return type after the parameters and returns with Return:

VB
Function Area(width As Double, height As Double) As Double
    Return width * height
End Function

Dim a As Double = Area(3, 4.5)       ' 13.5
Console.WriteLine(Area(2, 2) + 1)    ' 5

Every code path must return a value; the compiler warns when one does not. The old style assigns to the function's own name (Area = width * height); prefer Return.

Visibility keywords (Public, Private, Friend) and Shared apply when procedures live in classes; procedures in a Module are shared automatically.

C# Stand-in (C#): a procedure and a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ByVal and ByRef

By default (and since VB 2002, implicitly) parameters are passed ByVal: the procedure receives a copy of a value (or a copy of a reference). Assigning to the parameter inside does not change the caller's variable. ByRef passes the variable itself, so changes are visible to the caller.

VB
Sub AddTen(ByVal n As Integer)
    n += 10             ' changes only the local copy
End Sub

Sub AddTenRef(ByRef n As Integer)
    n += 10             ' changes the caller's variable
End Sub

Dim x As Integer = 1
AddTen(x)
Console.WriteLine(x)    ' 1
AddTenRef(x)
Console.WriteLine(x)    ' 11

With a reference type like a List, ByVal copies the reference, so the procedure can still modify the same object (add items) but cannot make the caller's variable point at a different list. ByRef can do both. Use ByRef sparingly: returning a value is usually clearer. When you need to return several values, return a Tuple:

VB
Function MinMax(values As Integer()) As (Min As Integer, Max As Integer)
    Return (values.Min(), values.Max())
End Function

Dim r = MinMax({4, 9, 2})
Console.WriteLine($"{r.Min} {r.Max}")     ' 2 9
C# Stand-in (C#): by value, by reference, and tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Optional parameters and named arguments

Give a parameter a default with Optional. Optional parameters must come last.

VB
Function FormatPrice(amount As Decimal, Optional currency As String = "USD",
                     Optional decimals As Integer = 2) As String
    Return currency & " " & amount.ToString("F" & decimals)
End Function

Console.WriteLine(FormatPrice(9.5D))                   ' USD 9.50
Console.WriteLine(FormatPrice(9.5D, "EUR"))            ' EUR 9.50
Console.WriteLine(FormatPrice(9.5D, decimals:=0))      ' USD 10 (rounded by the format)

name:=value is a named argument: you can skip optional parameters and pass arguments in any order. It also documents intent at the call site.

ParamArray: any number of arguments

ParamArray accepts zero or more values as an array and must be the last parameter:

VB
Function Sum(ParamArray numbers() As Integer) As Integer
    Dim total As Integer = 0
    For Each n As Integer In numbers
        total += n
    Next
    Return total
End Function

Console.WriteLine(Sum())           ' 0
Console.WriteLine(Sum(1, 2, 3))    ' 6

Overloading

Several procedures can share a name if their parameter lists differ. The compiler picks the best match from the arguments. The return type alone is not enough to tell overloads apart.

VB
Function Describe(value As Integer) As String
    Return "Integer " & value
End Function

Function Describe(value As String) As String
    Return "Text '" & value & "'"
End Function

Function Describe(value As Integer, scale As Double) As String
    Return "Scaled " & (value * scale)
End Function

In classes you may also mark a method Overloads explicitly when it hides a base member of the same name.

C# Stand-in (C#): optional, named and params

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Recursion

A procedure may call itself. A recursive procedure needs a base case that stops the calls and a step that moves toward it.

VB
Function Factorial(n As Integer) As Long
    If n <= 1 Then Return 1       ' base case
    Return n * Factorial(n - 1)   ' recursive step
End Function

Console.WriteLine(Factorial(5))   ' 120

Without a base case the calls never stop and the program ends with a StackOverflowException, which cannot be caught.

Lambdas and procedure variables

A lambda is an unnamed function you can store in a variable or pass to another procedure. Func(Of ..., TResult) represents functions that return a value, Action(Of ...) those that do not.

VB
Dim square As Func(Of Integer, Integer) = Function(x) x * x
Dim show As Action(Of String) = Sub(s) Console.WriteLine("-> " & s)

show(square(9).ToString())       ' -> 81

Dim evens = Enumerable.Range(1, 10).Where(Function(n) n Mod 2 = 0)
Console.WriteLine(String.Join(",", evens))   ' 2,4,6,8,10

Lambdas are the foundation of LINQ (see Collections and LINQ) and event handling (Events and Delegates).

Scope and good design

  • Parameters and locals exist only during the call.
  • Keep procedures short and give them one job; a name starting with a verb (CalculateTax, LoadCustomers) tells the reader what happens.
  • Prefer returning values to changing global state.
  • Document with ''' XML comments so IntelliSense shows tooltips.
C# Stand-in (C#): recursion and lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between a Sub and a Function?

    A Function declares a return type and uses Return value; a Sub just performs actions.
  2. 2. After calling AddTenRef(x) with a ByRef parameter that adds 10, what happens to x?

    ByRef passes the variable itself, so changes inside the procedure are visible to the caller.
  3. 3. How do you skip an optional argument and set a later one?

    Named arguments (name:=value) let you pass only the arguments you want.
  4. 4. What is required for a recursive procedure to end?

    Without a base case the calls continue until the stack overflows.
  5. 5. Which of these can distinguish two overloads?

    Overloads must differ in their parameter lists.

Summary

  • Sub performs actions; Function returns a value with Return.
  • Parameters are ByVal (copy) by default; ByRef shares the caller's variable; tuples return several values cleanly.
  • Optional, named arguments (:=) and ParamArray make calls flexible; overloads share a name with different parameter lists.
  • Recursion needs a base case; lambdas (Function(x) ..., Sub(s) ...) are values.
  • Keep procedures small, well named and free of hidden state.

Next: Arrays