Start learning free

LESSON 263 OF 674 · TUPLES, SORTING & BUILT-INS

Tuples in C#

Lesson

TL ; DR:

A tuple keeps a few values together, like a movie's title and year. Give its parts names and read them with a dot, or unpack them into variables.


(string Title, int Year) movie = ("Frozen", 2013);   // a tuple

Console.WriteLine(movie.Title);                      // Frozen

Console.WriteLine(movie.Year);                       // 2013

var (title, year) = movie;                           // unpacking

Console.WriteLine(title + " " + year);               // Frozen 2013


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. C# keeps a few values like these in a tuple.

  • ("Frozen", 2013) is a tuple. The values go in parentheses, separated by commas.
  • (string Title, int Year) is its type, with a name for each part.
  • movie.Title is "Frozen", and movie.Year is 2013.
  • Without names, the parts are Item1 and Item2. Names make the code easier to read.

var (title, year) = movie; unpacks the tuple into two new variables, in the same order as its parts.

A method can return a tuple. Its return type is the tuple type, like (string Title, int Year). Then return (a, b); builds it.

Watch the parentheses. (string Title, int Year) is a type, and ("Frozen", 2013) is a value.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make SplitTime return its tuple: the whole hours and the minutes left.

Then unpack pet into name and age.

Last, call SplitTime(135). Unpack its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check