DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Mandar Badve
Mandar Badve

Posted on • Originally published at blog.mandarbadve.com on

Tuple, a new data structure in C#

This post was originally published on blog.mandarbadve.com

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:

Description

|
| 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. |

Top comments (0)

πŸ”  Find your favorite font

Β 
You can change your default font in Settings.