Functions in VB.net
The functions in VB.net is a separate group of codes that are used to perform a specific task when the defined function is called in a program.
After the execution of a function, control transfers to the main() method for further execution. It returns a value.
In VB.net, we can add multiple functions to a program to carry out different functionalities. By minimizing duplicate code, the method also helps with code reuse.
For instance, we can easily write a function and call it whenever necessary if we need to employ the same functionality across a program.
VB.net Function Definition
The name, parameters, and body of a function are declared using the Function statement.
The syntax for the Function Statement in VB.net:
'syntax for the function statement'
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function1. Modifiers
define the function’s access level; options include Public, Private, Protected, Friend, and Protected Friend. You should also include details on overloading, overriding, sharing, and shadowing.
2. FunctionName
Indicates the name of the function that should be unique.
3. ParameterList
Specifies the list of the parameters.
4. ReturnType
specifies the data type of the variable the function returns
The function FindMax in the following code snippet returns the greater of two integer values given two values.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End FunctionFunction Returning a Value in VB.net
In VB.Net, a function has two different ways to return a value to the caller code.
- By using the return statement
- By assigning the value to the function name
The following example demonstrates using the FindMax function:
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End ModuleWhen the above code is compiled and executed, it produces the following result:
Max value is : 200
You can test the above example here! ➡ VB.net Online Compiler
Recursive Function in VB.net
A function in VB.net is referred to as recursive if it keeps calling itself until the specified condition is met.
Numerous mathematical problems, such as producing the Fibonacci series and computing the factorial of a number, can be solved using recursive functions.
Following is an example that calculates factorial for a given number using a Recursive function in VB.net.
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End ModuleWhen the above code is compiled and executed, it produces the following result:
Factorial of 6 is : 720
Factorial of 7 is : 5040
Factorial of 8 is : 40320
You can test the above example here! ➡ VB.net Online Compiler
Param Arrays in VB.net
You might not always be certain of the number of arguments supplied as a parameter when declaring a function or sub process.
These situations call for the use of VB.Net param arrays (also known as parameter arrays).
Example Program of Param Arrays in VB.net:
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0
For Each i In arr
sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End ModuleWhen the above code is compiled and executed, it produces the following result:
The sum is: 2938
You can test the above example here! ➡ VB.net Online Compiler
Passing Arrays as Function Arguments in VB.net
In VB.net, you can pass an array as a function argument.
Example Program for Passing Arrays as a Function Arguments in VB.net.
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0
For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End ModuleWhen the above code is compiled and executed, it produces the following result:
Average value is: 214.4
You can test the above example here! ➡ VB.net Online Compiler
Summary
A Function returns a value as opposed to a Sub. If we don’t have a return value, we must use a Sub.
We must return this value. We are able to assign to a Function’s output.
PREVIOUS
NEXT
Common use cases for Functions
Functions shows up frequently in production VB.NET codebases. The most common patterns:
- Business logic layer. Encapsulate rules and workflows separate from the UI.
- Data access patterns. Bridge between UI events and database operations cleanly.
- Utility helpers. Reusable methods for string processing, date arithmetic, or format conversion.
- Integration with .NET libraries. Interoperate with System.IO, System.Net, System.Text.RegularExpressions, and more.
- Legacy migration. Modernize VB6 code by wrapping old logic in idiomatic VB.NET constructs.
Working code example
Public Module Program
Public Sub Main(args As String())
' Practical demonstration of Functions
Dim result As String = ProcessData("sample input")
Console.WriteLine("Result: " & result)
Console.ReadKey()
End Sub
Private Function ProcessData(input As String) As String
If String.IsNullOrWhiteSpace(input) Then
Return "empty"
End If
Return input.ToUpper()
End Function
End Module
Best practices when working with Functions
- Explicit typing. Enable Option Strict On at the project level to force compile-time type checking.
- Namespace hygiene. Group related types under project-specific namespaces to avoid conflicts with .NET Framework types.
- Consistent naming. Follow Microsoft’s VB.NET style guide: PascalCase for public members, camelCase for locals.
- Error handling with Try/Catch. Prefer specific exception types over catch-all Exception blocks.
- Modern language features. Use string interpolation, LINQ, and Async/Await where they clarify intent.
Common pitfalls
- Late binding. Without Option Strict, VB.NET falls back to late-binding, hiding bugs until runtime.
- Nothing vs empty string. String.IsNullOrEmpty and String.IsNullOrWhiteSpace catch both cases; avoid checking IsNothing alone.
- Integer overflow. Use Long or Decimal for arithmetic that may exceed Int32.MaxValue.
- Date parsing across cultures. Always pass CultureInfo.InvariantCulture when serializing dates for storage.


