Tuple
In VB.NET a Tuple
groups related pieces of data. With the useful Tuple
type, we pass multiple values to a function or return multiple values.
This type is useful for grouping relating values into a small class
. Using tuples tends to reduce program complexity—but they are not always ideal.
We create a Tuple
by using the VB.NET language's syntax for generic constructs. We must specify each type of the fields in the Tuple
at construction time.
Item1
, Item2
, and Item3
. We can only read these fields. We cannot set them.String
and Boolean
for our tuple's 3 items.Module Module1 Sub Main() ' Create new tuple instance with three items. Dim tuple As Tuple(Of Integer, String, Boolean) = _ New Tuple(Of Integer, String, Boolean)(1, "dog", False) ' Test tuple properties. If (tuple.Item1 = 1) Then Console.WriteLine(tuple.Item1) End If If (tuple.Item2 = "rodent") Then Console.WriteLine(0) End If If (tuple.Item3 = False) Then Console.WriteLine(tuple.Item3) End If End Sub End Module1 False
How can you use the Tuple
type with functions and subroutines in the VB.NET language? We first instantiate the Tuple
as we did above.
Tuple
value can be declared in much the same way, and is not shown here.StringBuilder
) in a Tuple
.Imports System.Text Module Module1 Sub Main() ' Use this object in the tuple. Dim builder As StringBuilder = New StringBuilder() builder.Append("cat") ' Create new tuple instance with 3 items. Dim tuple As Tuple(Of String, StringBuilder, Integer) = _ New Tuple(Of String, StringBuilder, Integer)("carrot", builder, 3) ' Pass tuple as parameter. F(tuple) End Sub Sub F(ByRef tuple As Tuple(Of String, StringBuilder, Integer)) ' Evaluate the tuple. Console.WriteLine(tuple.Item1) Console.WriteLine(tuple.Item2) Console.WriteLine(tuple.Item3) End Sub End Modulecarrot cat 3
A tuple can be used to return 2 or more values from a Function. We just declare the return type of the Function to be the required Tuple
.
Item1
and Item2
.Module Module1 Function GetTwoValues() As Tuple(Of Integer, Integer) ' Return 2 values from this Function. Return New Tuple(Of Integer, Integer)(20, 30) End Function Sub Main() Dim result As Tuple(Of Integer, Integer) = GetTwoValues() Console.WriteLine("RETURN VALUE 1: {0}", result.Item1) Console.WriteLine("RETURN VALUE 2: {0}", result.Item2) End Sub End ModuleRETURN VALUE 1: 20 RETURN VALUE 2: 30
A VB.NET class
is self-documenting. Field names, and the type name, help us remember our intentions. But a tuple, which lacks those names, may be harder to understand.
The Tuple
type is a clearly useful one in the VB.NET language. It provides a mechanism to create a class
with several items in it without a separate type definition.