Naming the steps
Every program bigger than a page is made of named pieces: "calculate the tax", "print the receipt", "find the cheapest supplier". In Visual Basic those pieces are procedures. Choosing them well, giving them clear names and clear parameters, is what makes a program maintainable by someone else. And in Visual Basic in particular, a lot of maintenance work happens inside procedures written years ago, so it pays to understand exactly how arguments are passed and what a procedure can change.
This lesson covers the two kinds of procedure, the many ways of declaring parameters, a few features peculiar to Visual Basic (such as Static locals and assigning a result to the function's own name), and the functional tools Visual Basic shares with C#: lambdas and delegates, which LINQ in a later lesson depends on.
Subs, Functions and parameters
Definition— Sub and Function
A Sub procedure performs an action and returns no value. A Function procedure returns a value, whose type follows As after the parameter list. Both are declared with a parameter list in parentheses, and both end with their own End keyword. Inside a function, Return value leaves it with a result.
Definition— ByVal and ByRef
A ByVal parameter receives a copy of the argument's value; changing the parameter does not affect the caller's variable. A ByRef parameter is another name for the caller's variable itself; assigning to it changes the caller's variable. In Visual Basic .NET, ByVal is the default.
Analogy, not a formal construction
Passing ByVal is like handing a colleague a photocopy of a form: they can scribble on it, and your original is untouched. Passing ByRef is like handing them the original itself. And passing an object ByVal is like handing them a photocopy of a card that says which filing cabinet holds the original: they cannot change your card, but they can walk to the cabinet and change what is inside.
Option Strict On
Module Program
' A Sub does something; a Function returns a value.
Sub PrintReceipt(item As String, price As Decimal, Optional quantity As Integer = 1, Optional currency As String = "EUR")
Console.WriteLine($"{quantity} x {item,-8} {price * quantity,8:F2} {currency}")
End Sub
Function Total(ParamArray amounts() As Decimal) As Decimal
Dim sum As Decimal = 0
For Each a In amounts
sum += a
Next
Return sum
End Function
' Overloads: same name, different parameter lists.
Function Area(side As Double) As Double
Return side * side
End Function
Function Area(width As Double, height As Double) As Double
Return width * height
End Function
' ByVal (the default) passes a copy; ByRef passes the caller's variable itself.
Sub AddTenByVal(ByVal n As Integer)
n += 10
End Sub
Sub AddTenByRef(ByRef n As Integer)
n += 10
End Sub
Sub Main()
PrintReceipt("bread", 2.4D)
PrintReceipt("eggs", 0.3D, 12)
PrintReceipt("tea", 350D, currency:="KES") ' named argument, skipping quantity
Console.WriteLine($"Total: {Total(2.4D, 3.6D, 350D)}")
Console.WriteLine($"Areas: {Area(3)} {Area(2, 4.25)}")
Dim x As Integer = 5
AddTenByVal(x)
Console.WriteLine($"after ByVal: {x}")
AddTenByRef(x)
Console.WriteLine($"after ByRef: {x}")
End Sub
End ModuleIt prints:
1 x bread 2.40 EUR
12 x eggs 3.60 EUR
1 x tea 350.00 KES
Total: 356.0
Areas: 9 8.5
after ByVal: 5
after ByRef: 15- Optional parameters declare a default value; callers can leave them out. They must come after the required parameters.
- Named arguments use
:=, as incurrency:="KES". They let a caller skip an optional parameter in the middle and make calls with several similar values self-explanatory. ParamArrayaccepts any number of arguments as an array. It must be the last parameter.- Overloading: several procedures can share a name if their parameter lists differ; the compiler chooses by the arguments. (
Area(3)passes an integer, which widens toDouble.) ByValandByRef:AddTenByValchanged its copy, and the caller'sxstayed 5;AddTenByRefchangedxitself. UseByRefrarely, for procedures that genuinely must update a variable (such as theTryParsepattern); return values or tuples are clearer.- The sum
356.0has a trailing zero becauseDecimalkeeps the scale of its operands (2.4has one decimal place).
Note
An upgrade trap. In classic Visual Basic (VB6 and VBA), parameters were ByRef by default. A VB6 procedure that modified its parameter therefore changed the caller's variable; the same code in VB.NET, where the default is ByVal, silently stops doing so. Upgrade tools add explicit ByRef to preserve the old meaning, which is why migrated code is often full of ByRef that nobody really needs. Removing them one at a time, with tests, is a common clean-up. The same rule matters when you read VBA macros today.
ByVal copies the value of the argument, and for an array or an object that value is a reference. So a procedure that receives an array ByVal can still change its elements, which the caller will see; it just cannot make the caller's variable point to a different array. Exercise 1 tests this.
Static locals, recursion and tuples
Option Strict On
Module Program
' A Static local keeps its value between calls (a Visual Basic feature).
Function NextTicket() As Integer
Static counter As Integer = 100
counter += 1
Return counter
End Function
' Recursion: the greatest common divisor, by Euclid's method.
Function Gcd(a As Integer, b As Integer) As Integer
If b = 0 Then Return a
Return Gcd(b, a Mod b)
End Function
' Tuples (Visual Basic 15) return several values without declaring a type.
Function MinMax(values() As Integer) As (Low As Integer, High As Integer)
Dim low = values(0), high = values(0)
For Each v In values
low = Math.Min(low, v)
high = Math.Max(high, v)
Next
Return (low, high)
End Function
' Older style: assigning to the function's name sets its return value.
Function Describe(n As Integer) As String
Describe = If(n Mod 2 = 0, "even", "odd")
If n < 0 Then Describe &= " and negative"
End Function
Sub Main()
Console.WriteLine($"{NextTicket()} {NextTicket()} {NextTicket()}")
Console.WriteLine($"gcd(84, 36) = {Gcd(84, 36)}")
Dim range = MinMax({17, 4, 23, 9})
Console.WriteLine($"from {range.Low} to {range.High}")
Console.WriteLine($"spread {range.High - range.Low}; as a whole: {range}")
Console.WriteLine($"{Describe(4)}; {Describe(-3)}")
End Sub
End ModuleIt prints:
101 102 103
gcd(84, 36) = 12
from 4 to 23
spread 19; as a whole: (4, 23)
even; odd and negativeStaticlocal variables keep their value between calls:counteris initialised once, and each call toNextTicketcontinues from where the last one left off. It is a Visual Basic feature with no direct C# equivalent (C# would use a field). It is convenient, but it is hidden state: a function with aStaticvariable gives different answers to identical calls, which makes it harder to test. Use it sparingly, and remember that it is shared across threads.- Recursion works as in any language:
Gcdcalls itself with smaller arguments untilbis 0. - Tuples (Visual Basic 15, 2017) let a function return several values with names:
As (Low As Integer, High As Integer), andReturn (low, high). The caller readsrange.Lowandrange.High. Visual Basic does not support C#'s deconstruction syntax (var (a, b) = ...), so you read the named elements instead. For values that travel far, declare a class or structure (the next lesson). - Assigning to the function's name (
Describe = ...) sets the return value without leaving the function; execution continues, and the last value assigned is returned when the function ends. It is how classic Visual Basic returned values, and you will see it in old code.Returnis clearer, because it leaves immediately, and mixing the two styles in one function confuses readers.
Notice too the guard clause in Gcd: If b = 0 Then Return a handles the simplest case first and leaves at once. Exit Sub and Exit Function do the same for procedures that need to stop early, and writing the special cases first, then the normal case without deep nesting, keeps procedures easy to read.
Also notice Dim low = values(0), high = values(0): one Dim can declare several variables, and Option Infer gives both the type Integer.
Lambdas and delegates
Definition— Delegate
A type whose values refer to procedures with a particular signature. The .NET library provides generic delegates for almost every need: Func(Of Integer, Integer) is "a function taking an Integer and returning an Integer" (the last type is the result), and Action(Of String) is "a procedure taking a String and returning nothing".
A lambda is a procedure written inline, without a name: Function(n) n * n for a single expression, or a multi-line Function(n) ... End Function block, and Sub(s) ... for one that returns nothing. AddressOf refers to an existing named procedure as a delegate.
Option Strict On
Module Program
' A function that takes another function as a parameter.
Function ApplyToAll(values As Integer(), f As Func(Of Integer, Integer)) As Integer()
Dim result(values.Length - 1) As Integer
For i As Integer = 0 To values.Length - 1
result(i) = f(values(i))
Next
Return result
End Function
Function Triple(n As Integer) As Integer
Return n * 3
End Function
Sub Main()
Dim numbers = {1, 2, 3, 4}
' Single-line lambdas use Function(...) expression.
Dim squares = ApplyToAll(numbers, Function(n) n * n)
Console.WriteLine(String.Join(", ", squares))
' AddressOf passes an existing function.
Console.WriteLine(String.Join(", ", ApplyToAll(numbers, AddressOf Triple)))
' Multi-line lambdas, and Sub lambdas for actions.
Dim classify As Func(Of Integer, String) =
Function(n)
If n Mod 2 = 0 Then Return "even"
Return "odd"
End Function
Dim shout As Action(Of String) = Sub(s) Console.WriteLine(s.ToUpper() & "!")
shout(classify(7))
' Closures: a lambda can use, and change, variables around it.
Dim calls = 0
Dim counted As Func(Of Integer, Integer) =
Function(n)
calls += 1
Return n + 100
End Function
ApplyToAll(numbers, counted)
Console.WriteLine($"the lambda ran {calls} times")
' Sorting with a comparison lambda: by length, then alphabetically.
Dim names = {"Olusegun", "Ana", "Mei", "Fatoumata", "Ravi"}
Array.Sort(names, Function(a, b) If(a.Length <> b.Length, a.Length.CompareTo(b.Length), String.CompareOrdinal(a, b)))
Console.WriteLine(String.Join(" ", names))
End Sub
End ModuleIt prints:
1, 4, 9, 16
3, 6, 9, 12
ODD!
the lambda ran 4 times
Ana Mei Ravi Olusegun FatoumataApplyToAllis a higher-order function: it takes a function as an argument and applies it to each element. The same procedure computes squares and triples, depending on what it is given.Dim result(values.Length - 1) As Integersizes the new array correctly: remember that the number is the upper bound.- The multi-line lambda
classifyusesReturnlike any function;shoutis aSublambda stored in anAction. - Closures: the lambda
counteduses and changes the variablecalls, which belongs toMain. Lambdas capture variables, not copies of their values, socallswas 4 afterwards. Array.Sortaccepts a comparison lambda returning a negative number, zero or a positive number. Here it sorts by length, then alphabetically withString.CompareOrdinal.
Lambdas are the foundation of LINQ (Where(Function(x) x > 3)), of event handlers written inline, and of asynchronous code. Visual Basic introduced single-line lambdas in 2008 and multi-line lambdas in 2010.
Async functions
Since Visual Basic 11 (2012), a procedure marked Async can use Await to wait for an operation, such as a web request, a database query or a file read, without blocking its thread. It is the same model as C#'s async and await, built on the same Task type. An Async Function returns Task(Of T), and its callers await it in turn.
Option Strict On
Imports System.Threading.Tasks
Module Program
' An Async Function returns a Task; Await waits without blocking the thread.
Async Function FetchRateAsync(currency As String, delayMs As Integer) As Task(Of Decimal)
Await Task.Delay(delayMs) ' stands in for a call to a web service
Console.WriteLine($" received {currency}")
Return If(currency = "EUR", 0.0062D, 0.0076D) ' made-up rates, for illustration only
End Function
Async Function ConvertAllAsync(amountKes As Decimal) As Task
' Start both requests, then wait for both: they overlap in time.
Dim euro As Task(Of Decimal) = FetchRateAsync("EUR", 200)
Dim dollar As Task(Of Decimal) = FetchRateAsync("USD", 100)
Dim rates As Decimal() = Await Task.WhenAll(euro, dollar)
Console.WriteLine($"{amountKes} KES = {amountKes * rates(0):F2} EUR = {amountKes * rates(1):F2} USD")
End Function
Sub Main()
' Sub Main cannot be Async in Visual Basic, so a console program waits here, once.
ConvertAllAsync(5000D).GetAwaiter().GetResult()
End Sub
End ModuleIt prints:
received USD
received EUR
5000 KES = 31.00 EUR = 38.00 USDTask.Delay stands in for real input and output. ConvertAllAsync starts both requests before awaiting either, then uses Task.WhenAll to wait for both, so the two waits overlap: the dollar rate (100 ms) arrives before the euro rate (200 ms), and the whole conversion takes about as long as the slower request rather than the sum of both. Task.WhenAll returns the results in the order the tasks were given.
Visual Basic does not allow Sub Main to be Async (the compiler reports BC36934: The 'Main' method cannot be marked 'Async'), so a console program waits once, at the top, with GetAwaiter().GetResult(). In a Windows Forms or WPF application you would instead write Private Async Sub btnConvert_Click(...) Handles btnConvert.Click: event handlers are the one place where an Async Sub is appropriate, and the window stays responsive while the handler awaits. Everywhere else, an async procedure should be a Function returning a Task, so that callers can await it and see its exceptions.
From GOSUB to Function
Procedures were not always part of BASIC. In the line-numbered BASICs of the 1960s to the 1980s, a program jumped to a subroutine with GOSUB 1000 and came back with RETURN, with no parameters and no local variables: everything was global, and programs were notoriously hard to follow. Structured BASICs of the 1980s, such as Microsoft's QuickBASIC, introduced named SUB and FUNCTION procedures with parameters and local variables, and Visual Basic inherited them. Classic Visual Basic passed arguments by reference by default; Visual Basic .NET switched to by value, matching the rest of .NET. Lambdas arrived in 2008 with LINQ, and Async and Await in 2012.
Procedures in real Visual Basic codebases
Maintainers of older Visual Basic code meet the same patterns again and again. Some advice:
- Very long procedures. Event handlers in Windows Forms applications often grew to hundreds of lines (
Private Sub btnSave_Click(...)). The safest improvement is extract method: move a coherent block into a well-namedFunctionthat takes what it needs as parameters and returns its result. Visual Studio can do this automatically. - Modules full of global variables. A module-level
DimorPublicvariable is visible to every procedure, and old programs often coordinate through them. Prefer passing values as parameters and returning results, so that each procedure's inputs and outputs are visible in its signature. - Names. Procedures and parameters use PascalCase and camelCase respectively, as in C#. Because Visual Basic ignores case, a parameter cannot have the same name as its own function, a rule that surprises people translating from C#, where
Greeting(greeting As String)would be fine. - Optional parameters across assemblies. The default value of an optional parameter is copied into the caller's compiled code. If a library changes a default, callers compiled against the old version keep using the old default until they are rebuilt. For public library methods, overloads are safer than optional parameters.
Common misconceptions
Misconception
"ByVal means the procedure cannot change my data." It cannot change your variable. If the variable refers to an array or an object, the procedure receives the same reference and can change the array's elements or the object's properties.
Misconception
"A Function without a Return statement returns nothing." It returns whatever was last assigned to the function's name, or the type's default value (0, False or Nothing) if nothing was assigned. The compiler warns when a path through a function returns nothing explicitly.
Misconception
"Static means the same as Shared." Static applies to a local variable inside a procedure and keeps its value between calls. Shared applies to a member of a class and means it belongs to the class rather than to each object (the next lesson).
Exercises
1. Procedures and functions
CoreComputationalWhat does this program print?
Option Strict On
Module Program
Sub Change(ByVal arr() As Integer, ByVal n As Integer)
arr(0) = 99
n = 99
End Sub
Sub Main()
Dim values = {1, 2, 3}
Dim count = 1
Change(values, count)
Console.WriteLine($"{values(0)} {count}")
End Sub
End Module
2. Procedures and functions
CoreComputationalWhat does this program print?
Option Strict On
Module Program
Function Visit() As String
Static times As Integer
times += 1
Dim local As Integer
local += 1
Return $"{times}/{local}"
End Function
Sub Main()
Visit()
Visit()
Console.WriteLine(Visit())
End Sub
End Module
3. Procedures and functions
Warm-upComputationalWhat does this program print?
Option Strict On
Module Program
Function Welcome(name As String, Optional greeting As String = "Hello", Optional punctuation As String = ".") As String
Return $"{greeting}, {name}{punctuation}"
End Function
Sub Main()
Console.WriteLine(Welcome("Ama", punctuation:="!"))
End Sub
End Module
4. Procedures and functions
CoreComputationalWhat does this program print?
Option Strict On
Module Program
Function DigitSum(n As Integer) As Integer
If n < 10 Then Return n
Return n Mod 10 + DigitSum(n \ 10)
End Function
Sub Main()
Console.WriteLine(DigitSum(2026) + DigitSum(99))
End Sub
End Module
5. Procedures and functions
StretchHumanA VB6 procedure Sub Normalise(price As Currency) changes price inside its body, and callers rely on seeing the new value. After the code is moved to VB.NET with the parameter written as price As Decimal (no keyword), what happens?
6. Procedures and functions
CoreHumanWhich declarations compile under Option Strict On? (Choose all that apply.)
Further reading and resources
- Procedures in Visual Basic · MicrosoftSub, Function, Property and Operator procedures, parameters and arguments.
- Lambda expressions (Visual Basic) · MicrosoftSingle-line and multi-line lambdas, and how they capture variables.
- Static (Visual Basic) · MicrosoftHow Static locals keep their values, and their thread-safety.