What is c# tuplesAsk a question
The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types. It can be used where you want to have a data structure to hold an object with properties, but you don’t want to create a separate type for it.
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
The following example creates a tuple with three elements:
Tuple<int, string, string> person =
new Tuple <int, string, string>(1, “Steve”, “Jobs”);
In the above example, we created an instance of the Tuple which holds a record of a person. We specified a type for each element and passed values to the constructor. Specifying the type of each element is cumbersome. So, C# includes a static helper class Tuple which returns an instance of the Tuple<T> without specifying the type of each element, as shown below.
var person = Tuple.Create(1, “Steve”, “Jobs”);
A tuple can only include maximum eight elements. It gives a compiler error when you try to include more than eight elements.
var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
Accessing Tuple Elements
The elements of a tuple can be accessed with Item<elementNumber> properties e.g. Item1, Item2, Item3 and so on up to Item7 property. The Item1 property returns the first element, Item2 returns the second element and so on. The last element (the 8th element) will be returned using the Rest property.