A Tuple groups related pieces of data. With it we pass multiple values to a function or return multiple values. The Tuple type is useful for grouping relating values into a small class. It reduces program complexity.
To start, you can create a Tuple by using the VB.NET language's syntax for generic constructs. You must specify each type of the fields in the Tuple at construction time. Also, you must initialize the items to their final values.
Here:In this example, we read the three fields Item1, Item2, and Item3. You can only read these fields. You cannot set them.
Program that uses Tuple: VB.NET, .NET 4.0 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 Module Output 1 False
How can you use the Tuple type with functions and subroutines in the VB.NET language? First, you can instantiate the Tuple as we did above. The Tuple becomes part of the function signature.
Returning a Tuple value can be declared in much the same way, and is not shown here. Also, this example demonstrates the use of another type (a reference type, StringBuilder) in a Tuple.StringBuilder
Program that uses Tuple in function: VB.NET, .NET 4.0 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 three 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 Module Output carrot cat 3
Tip:There are more secrets to the Tuple type, and these are covered on this site in the C# language article on Tuple.Tuple
Note:Please scan that article for details about the Tuple implementation, and its conceptual place in software projects.
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. We cannot modify a Tuple already created.
Finally:The Tuple makes it easier to pass or return multiple values from a function. It fills a useful niche.