Tuple in C# with Example

In this article, we will know about Tuple in C#.

What is Tuple?

Tuple is a light-weight data structure that may contains 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 maximum of 8 elements. It will throw compile time error if you will add 9th elements. 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 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 below 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);

Nested Tuple

As we have learned that a Tuple can not include more than 8 elements. Nested Tuple will help to add more than 8 elements in 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 Rest keyword.

Below code snippet will display – Delhi

Console.WriteLine(data.Item1);

To access nested Tuple elements we will use below code. This code snippet will display Chennai. You may notice that below code contains Item1 2 times, this is because the Tuple elements are nested.

Console.WriteLine(data.Rest.Item1.Item1);

Now, what will happen if we will use data.Rest.Item1

This will give below output –

Q. Can we use Tuple as method parameter?

Answer – Yes, we can use Tuple as a method parameter.

Q. Can we use Tuple as return type?

Answer – Of course, we can use Tuple as method parameter.

Takeaway-

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 method parameter and return type.

Hope this article is helpful to you.

Please follow and like us:

Leave a Comment