Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 182 ยท Methods

Tuples and Deconstruction

Learn C# tuples - ValueTuple syntax, named elements, returning several values from a method, deconstruction, discards, tuple equality, and when to use records or out instead.

A method returns one value. But real questions often have two answers: "what are the smallest and largest items?", "did the parse work, and what number was it?", "what is the quotient and the remainder?". Before tuples you had to create a small class, use out parameters, or return an array and remember which slot meant what.

A tuple is a lightweight group of values that you create on the spot, with no type declaration. (3, "three") is a tuple of an int and a string. This lesson covers the syntax, naming the elements, returning several values, deconstructing a tuple into separate variables, discards, how equality works, how tuples are really stored, and when you should use something else.

Creating tuples

Write the values in parentheses, separated by commas. The tuple's type is written the same way, with types in place of values:

C# Tuple basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Without names, the elements are called Item1, Item2, and so on. A tuple can have many elements (up to 7 can be accessed directly as Item1 to Item7, with larger ones nested), but tuples with more than three or four elements are a sign you need a named type.

Printing a tuple shows its values in parentheses. The last line printed by GetType() shows the real type, a generic struct whose name starts with System.ValueTuple and lists the two Double type arguments. This tuple type is called ValueTuple, a value type (the older System.Tuple class is a reference type that you should avoid in new code).

Named elements

Item1 and Item2 tell the reader nothing. Give elements names, either in the type or in the value:

C# Naming tuple elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The third form is called tuple projection initializers (C# 7.1): when you build a tuple from variables, the variable names become element names. Names exist only at compile time, so at run time person.Name and person.Item1 are the same field. They are not part of the type's identity, which means (string Name, int Age) and (string, int) are interchangeable.

Use PascalCase for tuple element names (Name, Age), the same convention as public properties, because they behave like fields of a type.

Returning several values from a method

The most common use is a method with several results:

C# Returning a tuple from a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The return type (int Min, int Max) documents what each value means, and callers can use either result.Min or deconstruct. This is much cleaner than out parameters for simple cases, and it also works in async methods, where out is not allowed.

Deconstruction

Deconstruction unpacks a tuple's elements into separate variables in a single statement:

C# Deconstructing into variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The swap (a, b) = (b, a) is a favorite idiom. The right side is built completely first (a tuple holding the old values of b and a), and only then assigned, so no value is overwritten too early.

Discards

When you only need some of the values, use _ (a discard) for the others. A discard is not a variable; it just says "I don't need this":

C# Discards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Deconstructing your own types

Any type can support deconstruction by providing a Deconstruct method with out parameters. Records already do this for their positional properties, and you can add Deconstruct to a class:

C# A Deconstruct method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Tuple equality

Tuples support == and != (C# 7.3). Two tuples are equal when they have the same number of elements and each pair of elements is equal, compared in order. The comparison stops at the first difference:

C# Comparing tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

That last use is very practical: Dictionary<(int, int), string> is the quickest way to key a dictionary by two values such as grid coordinates. ValueTuple also implements IComparable, so lists of tuples can be sorted, element by element.

Tuples are mutable value types

A ValueTuple is a struct with public mutable fields. You can assign to an element, but because tuples are copied on assignment, changes to a copy do not affect the original:

C# Tuples are copied

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Mutating tuples tends to produce confusing code, especially in a list: list[0].Count = 5 is a compile error because list[0] returns a copy. Treat tuples as immutable data.

Tuples, records, structs and out parameters

Need Best choice
Return 2-3 values from a private or local method Tuple
Return a result shared across your public API record or a small class
Bool + value pattern like TryParse out parameter (works with if)
Data you keep, pass around, or serialize record with a real name
Composite dictionary key Tuple or record struct

Why prefer a record for public APIs? A named type has documentation, can have methods and validation, can grow new properties without breaking callers, and shows up in IntelliSense and error messages with a meaningful name. A tuple signature (int, int, string) is only understandable through its element names, which are not enforced by the type system.

C# The same result three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For TryParse-style APIs the out version is still the most readable at the call site (if (int.TryParse(s, out var n))). Use tuples when you want everything together as one expression.

Pitfalls to remember

  • Names are not enforced. A method returning (int Width, int Height) can be assigned to a variable of type (int Height, int Width), and the values keep their positions, not their names. The compiler may only warn.
  • Item1 is meaningless to readers. Always name public tuple elements.
  • Large tuples are hard to read. More than three elements is usually a design smell.
  • Reference vs value semantics: a tuple containing a List copies the reference, not the list.
  • Serialization of tuples by libraries often loses element names, so use a record for data you send over the wire.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression creates a tuple with named elements?

    Named elements use a colon after the name. The type of this expression is (string Name, int Age).
  2. 2. What does the swap statement (a, b) = (b, a); do?

    The right-hand tuple captures both current values first, then they are assigned, so the values are exchanged correctly.
  3. 3. What is the result of (1, 'a') == (1, 'a') in C#?

    Since C# 7.3 tuples support == and != by comparing each element in order. ValueTuple is a struct, so equality is by value.
  4. 4. When should you prefer a record over a tuple?

    A record has a real name, can carry methods and validation, and can grow without breaking callers. Tuples are best for short-lived local results.
  5. 5. What does the discard _ do in var (q, _) = Divide(17, 5);?

    A discard tells the compiler you do not need that value, so no variable is created for it.

Summary

  • A tuple groups values without declaring a type: (int, string); the runtime type is the struct ValueTuple.
  • Name elements with (string Name, int Age); names are compile-time only.
  • Return several values with a tuple, then deconstruct: var (min, max) = MinMax(data);.
  • Use _ to discard values you don't need; (a, b) = (b, a) swaps two variables.
  • Tuples support == and != and work as dictionary keys.
  • ValueTuples are mutable copies; for public APIs and long-lived data prefer records, and for Try patterns prefer out.

Next: Arrays