A tuple is a data structure that can contain elements of data types that are different. A tuple allows the return of several values without having to use the
out keyword. It also allows the storage of elements that are duplicate. The maximum number of elements that a tuple can have are 8.
Prior to tuples, if a user wanted to return more than one value, the user would have to use in addition to
out, a struct or class.
Creating a tuple
There are two ways to create a tuple: Using the tuple’s constructor or using the Create method.
Using the constructor
Let’s say that we want to create a tuple with three elements called student. This tuple will have the data types: int, string, and int. It will hold the student’s Id, name, and age:
Tuple<int,string, int> student = new Tuple<int, string, int>(1234567, "Ryan Smith", 19);
Using the create method
If we want to create the same tuple as above using the
create method, we would do the following:
var student = Tuple.Create<int, string, int>(1234567, "Ryan Smith", 19);
Accessing elements of a tuple
We access the elements of a tuple using the following manner:
Let’s output the student’s name from the tuple called student above. We know that the student’s name is the second element, so we proceed as follows:
Console.WriteLine(student.Item2); //Ryan Smith
Accessing the last element of a tuple
If we want to access the last element of a tuple, we use the
var someTuple = Tuple.Create("John", "Robert", "Sally", "Susan", 11, 56, 67, 334); Console.WriteLine(someTuple.Rest); //(334)
You can create a nested tuple by placing a tuple inside another tuple and accessing the nested tuple using the
Rest method. Although the nested tuple can be placed anywhere inside a tuple, you should keep it at the end in order to access it using the
Rest method. Otherwise, you will have to access it using the name of the tuple followed by the item number (e.g.
var anotherTuple = Tuple.Create("John", "Robert", "Sally", "Susan", 11, 56, 67, Tuple.Create(100, 200, 300, 400)); Console.WriteLine(anotherTuple.Item1); //John Console.WriteLine(anotherTuple.Item2); //Robert Console.WriteLine(anotherTuple.Item3); //Sally Console.WriteLine(anotherTuple.Item4); //Susan Console.WriteLine(anotherTuple.Item5); //11 Console.WriteLine(anotherTuple.Item6); //56 Console.WriteLine(anotherTuple.Item7); //67 Console.WriteLine(anotherTuple.Rest); ((100, 200, 300, 400))