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.
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.
ByRef
. It sets the two output parameters before it exits. We can use them in the calling location.KeyValuePair
. It returns a KeyValuePair
created by calling the New KeyValuePair
constructor.Tuple
class
to return multiple values. A tuple can return many more than two values, but we just show two here.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
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.
ByRef
argument to return a value will yield code that is easily understood by others.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.