Tuples in C#

Any function we use in C# can return a maximum of a single value that can be a string, int or any other type, depending on our requirements. If more than one value is to be returned, we use various types of approaches, like using a Dictionary with a key-value pair or a new container class, with properties of this class being the data/parameters we would like to be returned from that function or use the out or ref based parameters. All these are good if they are fulfilling our requirements. But C# provides a Tuple class that can be used and can be a more efficient way to return multiple values from a function.

Tuples were introduced in C# 4.0. In simple terms, you can define a tuple as a single record of various types of data. For example, a single record with UserId, FirstName, LastName, Salary and so on can be called a tuple. It's not necessary that all these attributes are of the same user. UserId can be of one user, FirstName could be of another user, Salary could be of third user and so on.

Enough of the theory, let's see in practice. There are two ways to create a tuple. The first is to simply create a new instance of the Tuple class and explicitly specify the types of elements this tuple can have. The values to be stored in this tuple are passed in its parameterized constructor. See the code below:



Accessing the parameters is very easy. Just use _tuple.Item1 and _tuple.Item2 where Item1 and Item2 are the elements at the first and second position of the tuple. See the code below:



So the complete code becomes:



Another way to create a tuple is use the Create method of the tuple class. However, the method to access the elements remain the same. See the code below:



So these were two separate ways to create a tuple. An important point is that there is a limit of 7 elements that a tuple can hold. The eighth element can only be another tuple. Although if you try to declare an eighth element of any type other than a tuple type, there will be no compile time error. But it will break at run-time with the error:

The last element of an eight element tuple must be a Tuple

So if you need to have more than 7 elements in a tuple, you can use the eighth placeholder as a nested tuple. To access its element, you have a property named Rest that further contains the elements of the nested tuple as Item1, Item2 and so on. See the code below:



So this was about tuples. I hope it helps you. Happy coding!


Similar Articles