Tuples in C#

Posted by

A tuple is a data structure that can store multiple values of different data types in a single unit. In C#, tuples are used to return multiple values from a method, or to store a group of values without creating a separate class.

Creating a Tuple

A tuple can be created by using the ValueTuple structure. The values can be assigned to the elements of the tuple by using parentheses () and separating the values by commas. Here is an example of how to create a tuple:

var myTuple = (1, "Hello", 3.14);

You can also assign values to each element by using the names of the elements:

var myTuple = (num: 1, message: "Hello", pi: 3.14);

Retrieving Values from a Tuple

To retrieve the values from a tuple, you can use the property names or index positions. Here is an example of how to retrieve values using both methods:

var myTuple = (num: 1, message: "Hello", pi: 3.14);

int num = myTuple.num;
string message = myTuple.message;
double pi = myTuple.pi;

//or

int num = myTuple.Item1;
string message = myTuple.Item2;
double pi = myTuple.Item3;

Using Tuples in Methods

Tuples can be used to return multiple values from a method without using out parameters or creating a separate class. Here is an example of a method that returns a tuple:

public static (int, string, double) GetValues()
{
    return (1, "Hello", 3.14);
}

And here is how you would call the method:

var myTuple = GetValues();

Decomposing a Tuple

You can also “decompose” a tuple by using the var keyword and providing a list of variables to store the values. Here is an example:

var (num, message, pi) = GetValues();

This is a brief tutorial on how to use C# tuples. With tuples, you can easily store and retrieve multiple values of different data types in a single unit.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.