Multiple return values. A function in VB.NET can only return one value—this can be a value type or a reference type (like a Class). But one value is not always sufficient.
With ByRef arguments, we can set multiple output values. And with a structure like KeyValuePair (or a class like Tuple) we can return multiple values as one.
Example. This program has several versions of a GetTwoNumbers function. These all return 2 Integers, either by using ByRef arguments or a container to store the result.
Part 4 We call the different versions of the GetTwoNumbers functions and print their output to verify their correctness.
Module Module1
Sub GetTwoNumbersA(ByRef number1 As Integer, ByRef number2 As Integer)
' Part 1: use ByRef parameters.
number1 = 2
number2 = 3
End Sub
Function GetTwoNumbersB() As KeyValuePair(Of Integer, Integer)
' Part 2: return a KeyValuePair.
Return New KeyValuePair(Of Integer, Integer)(2, 3)
End Function
Function GetTwoNumbersC() As Tuple(Of Integer, Integer)
' Part 3: return a tuple.
Return New Tuple(Of Integer, Integer)(2, 3)
End Function
Sub Main()
' Part 4: test the functions.
Dim number1 As Integer
Dim number2 As Integer
GetTwoNumbersA(number1, number2)
Console.WriteLine($"{number1} {number2}")
Dim result2 = GetTwoNumbersB()
Console.WriteLine($"{result2.Key} {result2.Value}")
Dim result3 = GetTwoNumbersC()
Console.WriteLine($"{result3.Item1} {result3.Item2}")
End Sub
End Module2 3
2 3
2 3
Some notes. Often ByRef arguments are easier to use. This probably depends on how a programmer is thinking. But introducing Tuples or Pairs seems excessively complex to me.
And The concept of reference, output parameters is well-known in the programming world.
So Using a ByRef argument to return a value will yield code that is easily understood by others.
Summary. With ByRef, KeyValuePair and Tuple, we return many values from VB.NET Subs and Functions. This approach is powerful. Not all methods logically return just 1 value.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 3, 2024 (new example).