Select Page

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 tuples, you need to define the data and the types of data that are within it. See the example below of a C# tuple:

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 on the Tuples 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 reference types and value types of any kind. It 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 types for it. Then you can place the array’s values in curly brackets.

Tuple Usage

One can use tuples in the following scenarios:

  • To return multiple values from a method without using ‘out’ or ‘ref’ parameters.
  • Passing multiple values to a method via a single parameter.
  • To hold a database record or values temporarily but not creating a separate class.

Tuple Limitations

  • It’s a reference type, not a value type. Tuple allocates on the heap and can lead to CPU intensive operations.
  • Limited to include eight elements. To store more elements, one needs to use nested tuples, but it can result in ambiguity.
  • A user can access tuple elements by using properties with a name pattern Item<elementNumber>. This does not make sense.

Final Thoughts about C# Tuple

The tutorial that we provided is succinct. For more information, follow the link below. You may email us with questions or queries.

Learn more about C# tuple by following the link.

Share This