Tuple is new feature added in C# 4.0 with dynamic programming. Tuple allow us to group a heterogeneous elements together. Tuple is new for the C# developers as it is already present in other languages like Python and F#.
Generally, In c# tuple is an ordered sequence, immutable ,heterogeneous and fixed size of an object.i.e.
ordered sequence :- It means that the order of an elements in tuple follow the order in which they are created.
immutable :- It means that once tuple is created then it cannot be modified.
heterogeneous :- It means that each element in tuple will be specific and independent to other element data type.
fixed size :- It means that the tuple size is set at the time of its creation.
Syntax for creating a tuple in C#:
var tuple1 = new Tuple<string, int>("Ankt", 35);
var tuple2 = Tuple.Create("Ankit", 35);
Tuple<int, string, DateTime> _cliente = Tuple.Create(2, "Asha", new DateTime(2016, 12,05));
Each tuple will contains only 8 elements. If we need to create a tuple more then 8 elements , we have to create nested Tuples. Even the eighth element of the tuple need to be create in another tuple.
See the below code:
var tupleItem = new Tuple<int,int,int,int,int,int,int,int>(1, 2, 3, 4, 5, 6, 7, 8);
When we execute the above line of code it will throw an exception “The eighth element must be a tuple“.
To execute the above line of code successfully, we need to modify the above code:
var tupleItem = new Tuple<int,int,int,int,int,int,int,Tuple<int>>(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8));
var tupleItem8 = tupleItem.Rest.Item4;
To create more then 8 elements in tuple, see the below code:
var tupleItem = new Tuple<int,int,int,int,int,int,int,Tuple<int,int,int>>
(1, 2, 3, 4, 5, 6, 7, new Tuple<int,int,int, int,int>(8,9,10));
<>var Item10 = tupleItem.Rest.Item4;
Some times we need to access a specific element of tuple then we have to use a ItemN property , where N is the position of the item.
var tupleItem = new Tuple<string, int>("Ankit", 25);
string UserName = tupleItem.Item1;
int Age = tupleItem.Item2;
After discussing about the tuples we understand that tuple is not a collection so we can iterate through tuple. A tuple is like an anonymous class with anonymous properties. Most we use a tuple where we need to create a class for storing a temporary data and where we need to return a more then one value from a function.