C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ByRef: The first version uses ByRef. It sets the two output parameters before it exits. We can use them in the calling location.
KeyValuePair: The second version uses KeyValuePair. It returns a KeyValuePair created by calling the New KeyValuePair constructor.
KeyValuePairVB.NET program that uses multiple return values
Module Module1
Sub TodayAndTomorrow(ByRef today As DateTime, ByRef tomorrow As DateTime)
today = DateTime.Today
tomorrow = DateTime.Today.AddDays(1)
End Sub
Function TodayAndTomorrow() As KeyValuePair(Of DateTime, DateTime)
Return New KeyValuePair(Of DateTime, DateTime)(
DateTime.Today, DateTime.Today.AddDays(1))
End Function
Sub Main()
Dim day1 As DateTime
Dim day2 As DateTime
TodayAndTomorrow(day1, day2)
Console.WriteLine(day1)
Console.WriteLine(day2)
Console.WriteLine()
Dim pair As KeyValuePair(Of DateTime, DateTime) = TodayAndTomorrow()
Console.WriteLine(pair.Key)
Console.WriteLine(pair.Value)
End Sub
End Module
Output
12/14/2014 12:00:00 AM
12/15/2014 12:00:00 AM
12/14/2014 12:00:00 AM
12/15/2014 12:00:00 AM
Tip: The Tuple is used in the same way as a KeyValuePair. It can return three, four, or more values with the same syntax form.
VB.NET program that uses Tuple
Module Module1
Function TodayAndTomorrow() As Tuple(Of DateTime, DateTime)
Return New Tuple(Of DateTime, DateTime)(
DateTime.Today, DateTime.Today.AddDays(1))
End Function
Sub Main()
Dim t As Tuple(Of DateTime, DateTime) = TodayAndTomorrow()
Console.WriteLine(t.Item1)
Console.WriteLine(t.Item2)
End Sub
End Module
Output
12/14/2014 12:00:00 AM
12/15/2014 12:00:00 AM
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.
And: ByRef arguments tend to defeat certain compiler optimizations. The JIT compiler in the .NET Framework has limits.