A function is a reusable block of code that performs a specific task and returns a value. Instead of writing the same logic multiple times, you can create a function and call it whenever needed. In this VB.NET Functions Tutorial, you'll learn VB.NET function declaration, understand VB.NET function syntax, explore ParamArray, and create your first function with an example.
What is a Function in VB.NET?
A Function in Visual Basic accepts input (optional), processes it, and returns a result. Functions help make your code modular, reusable, and easier to maintain.
Unlike a Sub procedure, which performs an action without returning a value, a Function always returns a value to the calling code.
VB.NET Function Declaration
A function is declared using the Function keyword, followed by its name, parameters, return type, and code block.
Function AddNumbers(num1 As Integer, num2 As Integer) As Integer
Return num1 + num2
End Function
This is the standard VB.NET function declaration and demonstrates the basic VB.NET function syntax.
VB.NET Function Example
The following example calls a function and displays the returned value.
Dim total As Integer
total = AddNumbers(10, 20)
Console.WriteLine(total)
This VB.NET function example shows how functions simplify code by reusing the same logic whenever it is needed.
VB.NET ParamArray
A ParamArray allows you to pass multiple values to a function without specifying the exact number of arguments.
Function Total(ParamArray numbers() As Integer) As Integer
Return numbers.Sum()
End Function
Use VB.NET ParamArray when the number of inputs can vary.
Best Practices
Give functions meaningful names such as CalculateTotal() or FindAverage().
Keep each function focused on one task.
Return the appropriate data type.
Avoid duplicating code by reusing functions.
Use ParamArray only when a variable number of arguments is required.
Learning Visual Basic .NET Functions is an important step toward writing modular and maintainable applications. Continue with the next tutorial on VB.NET Procedures or VB.NET Object-Oriented Programming to learn how larger applications are organized.