A tuple is a collection with a number of items that you cannot change once defined. The maximum number of items you can have in a tuple is 8. Note that Item8 is called TRest which can be another tuple if you want. This can be useful for creating objects that are only needed temporarily without defining a new class. The items in a tuple cannot be changed once they are set.
Creating a Tuple
The first step in creating a tuple is deciding the number of fields you need and the type of each field. A tuple is a generic class so it can hold data of any type.
Example of creating a 2 element tuple:
var tuple1 = new Tuple<int, int>(3, 4);
This Tuple has two elements which are both of type int. You can access the ith item by doing tuple1.Itemi where i is an integer greater than or equal to 1. The first item is Item1, the second is Item2 and so on.
Outputting items:
Console.WriteLine("Item 1: " + two.Item1);Console.WriteLine("Item 2: " + two.Item2);
When we run this code the output is:
tuple1.jpg 9.21K
215 downloadsAll items in a tuple do not have setters. This means that we cannot change the values. Observe what happens when we try to modify an item.
Try this code:
two.Item1 = 5;
This screenshot shows the error message that we get:
tuplesettererror.jpg 34.7K
218 downloadsThree-elements
Creating a tuple with three-elements is as simple as adding a third type parameter and supplying a third value.
Example:
Tuple<int, int, int> tuple3 = new Tuple<int, int, int>(3, 4, 5);
Then to access the third element we use tuple3.Item3 like this:
Console.WriteLine(tuple3.Item3);
When running this code the output is:
Quote
5
Eight elements
Example:
Tuple<int, int, int, int, int, int, int, int> eight = new Tuple<int, int, int, int, int, int, int, int>(1,1,1,1,1,1,1,1);
We can access the items using the class properties Item1, Item2, Item3, Item4, ..., Rest. This is the biggest size tuple that we can create.
Nested Tuples
Since a Tuple is restricted to 8 items if we want more than 8 items we have to use nested Tuples like this:
var nested = new Tuple<int, int, int, int, int, int, int, Tuple<double, double>>(1, 1, 1, 1, 1, 1, 1, new Tuple<double, double>(5.6, 3.4));
The idea is for the 8th element we create another tuple which can hold up to 8 more elements.
Then to output the 9th element use this code:
Console.WriteLine(nested.Rest.Item1);Rest gets the 8th element which is a two element tuple.
The output of the above code is:
Quote
5.6


Sign In
Create Account


Back to top









