In this article, we will know about Tuple in C#.
What is Tuple?
Tuple is a lightweight data structure that may contain different data types. It is introduced in C# 7.0.
Syntax to write Tuple
var tuple1 = new Tuple<string, int, string, string, int>
Following code snippet is used to create a tuple with 4 elements of different data types.
Tuple<int, string, string, string> employee = new Tuple<int, string, string, string>(1, "Ram", "Kumar", "India");
Create method of Tuple can include a maximum of 8 elements. It will throw a compile-time error if you add the 9th element. This method Creates a new 8-tuple or octuple.
Belo code will work perfectly.
var data = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
However, below code snippet will throw the error –
var data = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8,9);
How to access Tuple elements?
Use Item<Element Index Number> e.g. Item1, Item2, and so on to access Tuple elements.
Refer to the code snippet.
var data = Tuple.Create(1,"Ram","Kumar","India"); Console.WriteLine("ID - " + data.Item1); Console.WriteLine("First Name - " + data.Item2); Console.WriteLine("Last Name - " + data.Item3); Console.WriteLine("Country - " + data.Item4);
As we have learned that a Tuple can not include more than 8 elements. Nested Tuple will help to add more than 8 elements to it.
Syntax to use nested Tuple –
var data = Tuple.Create("Delhi","London","Washington","Toronto","Sydney","Auckland","Bangalore", Tuple.Create("Chennai","Tokyo","Mumbai"));
How to access Nested Tuple elements?
To access normal Tuple elements we can use Item1, Item2 and so on. But to access nested Tuple we will use the Rest keyword.
The below code snippet will display – Delhi
To access nested Tuple elements we will use the below code. This code snippet will display Chennai. You may notice that the below code contains Item1 2 times, this is because the Tuple elements are nested.
Now, what will happen if we will use data.Rest.Item1
This will give the below output –
Q. Can we use Tuple as a method parameter?
Answer – Yes, we can use Tuple as a method parameter.
Q. Can we use Tuple as a return type?
Answer – Of course, we can use Tuple as a method parameter.
A tuple is a data structure which is introduced in C# 7.0. It can include 8 elements, we can use nested Tuple if we want to add more elements. Tuple can be used as a method parameter and return type.
Hope this article is helpful to you.