How to Use Tuples

In C#, tuples are used to store data. It’s sort of like a variable, but in order for it to be a tuple it must contain more than one value. Each instance of a tuple has a fixed number of items within it (and each item has its own distinct type, eg. a variable or an int), and once the tuple has been created, it can’t be altered in any way. To create a tuple, you need to define both the data within it, and define what types of data are within it. See the example below:

using System;

class Program
{
    static void Main()
    {
       Tuple<int, string, bool> tuple =
	    new Tuple<int, string, bool>(6, "pizza", true);
    }
}

In the example above, a three item Tuple is defined. It’s defined as containing an int, string, and boolean data type, in that order, and then is followed by the actual int (6), string (“pizza”), and boolean (true) values. Tuples can contain both reference types and value types of any kind. Tuples can also contain less or more than (up to infinity, but creating a tuple with too many values could definitely slow down your code) 3 data types. Tuples can also contain arrays. Check out the example below:

using System;

class Program
{
    static void Main()
    {
       Tuple<int, string, bool> tuple =
	    new Tuple<int, string[], bool>(6, 
            food {"pizza", "fries", "ice cream"}, 
            true);
    }
}

As you can see, you must identify the data type as an array by placing brackets next to it when defining the data types for the tuple. Then you can place the array’s values in curly brackets.

Check out this page to learn more about the tuple class in C#.