Often, we want to return more than one value from a class method. Prior to the introduction of tuples in .NET, there were three common ways to do so.

Out parameters

Class or struct types

Anonymous types returned through a dynamic return type

Tuples solve this problem. Tuples aren’t new to C# or .NET. Tuples were first introduced as a part of .NET Framework 4.0.

A C# tuple is a data structure that provides an easy way to represent a single set of data. The System.Tuple class provides static methods to create tuple objects.

Tuples allow us to,

Create, access, and manipulate a data set

Return a data set from a method without using out parameter

Pass multiple values to a method through a single parameter

Create and Access Tuples

We can create a Tuple<> using its constructor or the "Create" method. The code snippet in Listing 1 creates a 3-tuple using a constructor. The tuple is a set of 3 data types including two strings and one int that represents an author's name, book title, and year of publication.

Nested Tuples

.NET framework supports tuples with up to seven elements. To have a tuple with more than seven elements, you can use the 8th element, TRest, to created nesting tuple objects. The code snippet in Listing 3 creates a tuple with a nested tuple inside it.

We can replace the above tuples code sample with the code listed in Listing 8, where the TupleReturnLiteral method returns a tuple type of three values.

// tuple return type

public (string, string, long) TupleReturnLiteral(long id)

{

string name = string.Empty;

string title = string.Empty;

long year = 0;

if (id == 1000)

{

name = "Mahesh Chand";

title = "ADO.NET Programming";

year = 2003;

}

// tuple literal

return (name, title, year);

}

Listing 8.

The code listed in Listing 9 calls the above TupleReturnLiternal method and returns a tuple variable. The code reads the tuple values using Item1, Item2, and Item3 of tuple and displays the values on the console.