Any function we use in C# can return maximum of single value which can be
string, intor any other type, as per our requirements. If more than one value is to be returned, we use different types of approaches, like using any
Dictionarywith key-value pair, or any new container class, with properties of this class being the data/parameters we would like to be returned from that function or use the
refbased parameters. All these are good if they are fulfilling our requirements. But C# provides a
Tupleclass, which can be used as more efficient way of returning 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 different types of data. For example, a single record with
UserId, FirstName, LastName, Salaryetc can be called as a tuple. It's not necessary that all these attributes are of the same user.
UserIdcan be of one user,
FirstNamecould be of another user,
Salarycould be of third user and so on.
Enough of theory, let's do some practical. There are two different ways how a tuple can be created. First is simply creating a new instance of the
Accessing the parameters is very easy. Just use
Tupleclass and explicitly specifying 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:
Item2are 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
Createmethod of the tuple class. However, the method to access the elements remains the same. See the code below:
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,which further contains the elements of the nested tuple as
Item2etc. See the code below:
So this was about the concept of tuples. Hope it helps you. Happy coding...!!!