Tuple, a new data structure in C#

Tuple is an interesting data structure in C#. It contains number and sequence. You can create tuple of 1 to 7 elements. Additionally you can create tuple of eight element using the TRest element. TRest element allows you to add nested tuple.

Let see example of basic tuple. We have student entity having marks fro seven subject. We can define this data structure by using tuple.

var tupleStudent = Tuple.Create("Mandar Badve", 87, 45, 76, 78, 64, 71, 80);
Console.WriteLine(""+ tupleStudent.Item1 + " got " + tupleStudent.Item2 + " marks in first subject.");
//// OUTPUT: Mandar Badve got 87 marks in first subject.
Console.WriteLine(""+ tupleStudent.Item1 + " got " + tupleStudent.Rest.Item1 + " marks in seventh subject.");
//// OUTPUT: Mandar Badve got 80 marks in seventh subject.

In above example first console will print the name of student accessed using Item1 of tuple and marks got in first subject accessed using Item2 of tuple. In second console we have access nested tuple using Rest property of tuple.

You can create tuple by using two ways.

  • Using constructor
var tupleUsingConstructor = new Tuple<string, int, int, int, int, int, int>("Mandar Badve", 87, 45, 76, 78, 64, 71);
  • Using helper method Create()
var tupleByHelperMethod = Tuple.Create("Mandar Badve", 87, 45, 76, 78, 64, 71, 80);

Create method have different overloads as follows:

Create<T1>(T1) Creates a 1-tuple, or singleton
Create<T1, T2>(T1, T2) Creates a 2-tuple, or pair.
Create<T1, T2, T3>(T1, T2, T3) Creates a 3-tuple, or triple.
Create<T1, T2, T3, T4>(T1, T2, T3, T4) Creates a 4-tuple, or quadruple.
Create<T1, T2, T3, T4, T5>(T1, T2, T3, T4, T5) Creates a 5-tuple, or quintuple.
Create<T1, T2, T3, T4, T5, T6>(T1, T2, T3, T4, T5, T6) Creates a 6-tuple, or sextuple.
Create<T1, T2, T3, T4, T5, T6, T7>(T1, T2, T3, T4, T5, T6, T7) Creates a 7-tuple, or septuple.
Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8) Creates a 8-tuple, or octuple.