Site icon

Tuple Types in C#

Tuple types in C# is a data structure that contains a sequence of elements of similar or different data types, it was introduced in C#.Net 4.0

C# Tuple is also known as immutable data type similar to anonymous types , that means once a Tuple type is created then all the properties of the Tuple types becomes read-only.

How to declare a C# Tuple type :

We can create a Tuple type by using Generic syntax as Tuple<T>, where T is the data type . Lets have a look at below example of a simple Tuple type.

Here in above, we have declared a Tuple type t that has a single string item as “Demo Tuple”. Lets look at below example Tuple that has 3 elements in it.

We can also use the implicitly typed variable (Var) to create above Tuple type as follows.

Accessing Tuple items in C# :

Once you declare a Tuple type , then the elements can be accessed with Item<ElementNumber>, e.g., Item1, Item2, and so on up to Item7 property. The Item1 property returns the first element, Item2 returns the second element, and so on.

For example, we can access above declared tuple object Tuple<string, string, decimal> student properties as follows.

Tuple declaration with 3 elements example :

Output to above sample code.

Tuple declaration with 4 elements example :

Lets look at below example of a tuple declaration having 4 elements of different type.

Output to above example :

Create C# tuple using Tuple.Create() method :

The System namespace has a non generic static Tuple class, which has number of static methods as Create , which acts as a factory method for creating new Tuple objects.

Nested Tuple types in C#:

Tuple<T> generic type supports item1, item2, item3 upto item7 elements, that can hold 7 element of similar or different data types.

If you want to create a new C# Tuple type to hold 8 or more elements, then you can do that by nesting another Tuple type in the last argument TRest property of Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> object.

In below example, we are nesting a new Tuple object new Tuple(8,9,10) as TRest parameter to the parent Tuple type.

Above declaration creates a nested Tuple type of 10 elements , You can access above Tuple object as follows.

Key Points :

Following are some of the key points about Tuple Types.

Tuple types in C# can be useful in some situations, however they have some limitations and constraints. In order to overcome this limitations, C# 7 came up with a new feature as ValueTuple . We will be discussing more about it in our next article.

Thanks for your time  feel free to provide your feedback and do check my other blogs on Dynamic type in C# , Nullable type in C# , Anonymous type in C# and Var Type in C#

Exit mobile version