C# – How to use named tuples

You can use tuples to contain multiple values and pass them around. By default, the tuple field names are unfriendly – Item1, Item2, etc… Instead of using these default names, you can name the tuple fields. Here’s an example of creating and using a named tuple:

var movieTuple = (title: "The Matrix", year: 1999); Console.WriteLine(movieTuple.title); // outputs The Matrix Console.WriteLine(movieTuple.year); // outputs 1999
Code language: C# (cs)

Meaningful names makes tuples easier to use. movieTuple.title is easier to understand and use than movieTuple.Item1. Behind the scenes, this is creating a ValueTuple<string, int> object. It has two fields: string Item1 and string Item2. Naming the fields title and year doesn’t change the underlying field names. It just lets you refer to the fields with the friendly names while coding.

I’ll show more examples of using named tuples.

Create a named tuple

There are three main ways to create a named tuple and give it values:

  • Declare the fields and assign the values at the same time (the field types are inferred):
var movie = (title: "The Matrix", year: 1999);
Code language: C# (cs)
  • Declare the tuple field names and types, then assign values to each field individually:
(string title, int year) movie; movie.title = "The Matrix"; movie.year = 1999;
Code language: C# (cs)
  • Declare the tuple field names and types, then assign values to all the fields at once (deconstruction assignment):
//Define structure (string title, int year) movie; //Assign all variables at once using deconstruction assignment movie = ("The Matrix", 1999);
Code language: C# (cs)

Return a named tuple from a method

You can return a named tuple from a method. This is a practical alternative to returning multiple out parameters. Here’s an example:

(string title, int year) GetMovie() { return (title: "Jurassic Park", year: 1993); }
Code language: C# (cs)

The caller has access to the named fields:

var movie = GetMovie(); Console.WriteLine(movie.title); //outputs Jurassic Park
Code language: C# (cs)

Named tuple as method parameter

You can use a named tuple as a method parameter. Here’s an example:

void SaveMovie((string title, int year) movie) { Console.WriteLine($"Saved movie {movie.title}"); }
Code language: C# (cs)

To call the method, create and pass in a tuple:

SaveMovie((title: "Jaws", year: 1975)); //Outputs "Saved movie Jaws"
Code language: C# (cs)

The caller isn’t required to pass in a named tuple. Just the tuple field types need to match (string, int). Here’s an example:

SaveMovie(("Jaws", 1975)); //Outputs "Saved movie Jaws"
Code language: C# (cs)

Leave a Comment