C# Tuple

C# Tuple is a data structure introduced in 4.0. It has elements with multiple parts i.e., more than one data type. In a Tuple, you can easily store duplicate elements. Also, a tuple returns values from a method without using the out parameter.

In C# Tuples, elements can only be added from 1 to 8. An error would be thrown, if you try to add more than 8 elements. However, you can use Nested Tuple to add more than 8 elements. To display the 8th element, use the Rest property. Rest, the 1st 7 items can be accessed using Item1, Item2, Item3, etc. properties.

Create a Tuple

To create a Tuple, there are two ways:

  • Create a Tuple using its Constructor
  • Create a Tuple using the Create() method

Create a Tuple using its constructor

Let us see an example of creating a tuple. We will also see how to access the values using the Item property. The 1st 7 items can be accessed using the Item property, i.e., Item1, Item2, Item3, etc. properties:

Output

Create a Tuple using the Create() method

Let us see an example of creating a tuple using the Create() method. We will also see how to access the values using the Item property. The 1st 7 items can be accessed using the Item property, i.e., Item1, Item2, Item3, etc. properties:

Output

Access Tuple elements/ items

Since, a Tuple in C# can have 8 elements, to display the 8th element, use the Rest property. Rest, the 1st 7 items can be accessed using the Item property, i.e., Item1, Item2, Item3, etc. properties.

Let us see an example and create a Tuple with 8 elements and access each element one by one:

Output

Nested Tuples

Use Nested Tuples in C# to add more than 8 elements. Those can be easily accessed using the Rest property in C#. Let us see an example:

Output

To get only the nested tuple, use the following:

The output would display the entire Nested Tuple:


Read More

C# - Installation and Setup
C# vs Java - Difference
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading