skip to content

Tuples and Deconstruction

ValueTuple gives named, mutable, value-typed tuples, and Deconstruct methods let any type split into variables. Interviewers ask tuples vs records vs out parameters.

on this pageshow

explore

questions

6

In C#, how does a tuple written as (int Id, string Name) differ from System.Tuple<int, string>?

level: juniorimportance: must knowfreq 60%

answer

  1. two types, one word
  2. struct versus class
  3. public fields versus read-only properties
  4. == on System.Tuple compares references

basics

~10 s

C# tuple syntax builds System.ValueTuple, a struct with public mutable fields and optional element names. System.Tuple is an older immutable class with read-only Item properties, no element names, and reference comparison under ==.

solid answer

~40 s

The `(int Id, string Name)` syntax compiles to `System.ValueTuple<int, string>`: a **struct**, so assignment and argument passing copy it, and its elements are public **fields** you can reassign. `Id` and `Name` are compiler aliases for `Item1` and `Item2`. `System.Tuple<int, string>` is the older **class**: assignment copies a reference, `Item1` and `Item2` are read-only properties (assigning one is CS0200), and there is no naming syntax. Equality differs as well: since C# 7.3 the compiler turns `==` on value tuples into an element-by-element comparison, while `==` on two `System.Tuple` instances compares references, even though `Equals` compares elements. Both can be deconstructed, and `ToValueTuple()` and `ToTuple()` convert between them, so new code uses value tuples and keeps `System.Tuple` for older APIs that already expose it.

code

csharp · 15 lines
csharp
using System;

(decimal Net, decimal Tax) quote = (100m, 20m);
var copy = quote;                 // ValueTuple is a struct: the whole value is copied
copy.Tax = 21m;                   // Item2 (named Tax) is a public, writable field
Console.WriteLine($"{quote} {copy}");

Tuple<decimal, decimal> legacy = Tuple.Create(100m, 20m);
// legacy.Item2 = 21m;            // error CS0200: Item2 is a read-only property
Console.WriteLine(legacy == Tuple.Create(100m, 20m));      // reference comparison
Console.WriteLine(legacy.Equals(Tuple.Create(100m, 20m))); // element-wise Equals
Console.WriteLine(quote == (100m, 20m));                   // compiler-generated element-wise ==

var (net, tax) = legacy;          // TupleExtensions.Deconstruct
Console.WriteLine($"{net} {tax} {legacy.ToValueTuple().GetType().Name}");

go deeper

for a junior

Recall that (int, string) syntax means System.ValueTuple, a struct with public fields, while System.Tuple is a read-only class you meet in older code.

for a middle

Explain the equality split: the compiler expands == on value tuples element by element, while == on System.Tuple compares references and only Equals compares elements.

for a senior

Show where System.Tuple still appears in older APIs, convert at that boundary with ToValueTuple, and explain why switching a public signature between the two breaks callers.

for a principal

Frame tuples as internal convenience and argue for named types on public contracts, naming what that rule costs in extra declarations and what it buys in readable call sites.

## Two types share the word "tuple" The .NET base class library has two unrelated families of generic tuple types, and C# treats them very differently: - **`System.ValueTuple<T1, ...>`** is the type behind C#'s built-in tuple syntax, introduced with C# 7. Writing `(int Id, string Name)` as a type, or `(42, "Ada")` as an expression, produces a `ValueTuple<int, string>`. - **`System.Tuple<T1, ...>`** is the older tuple class that predates the language syntax. You create one with `new Tuple<int, string>(...)` or `Tuple.Create(...)`; the language gives it no syntax of its own. Interviewers ask about the difference because the two types behave differently on every axis that matters in daily code: copying, mutation, naming and equality. ## Value type versus reference type `ValueTuple` is a **struct**. Assigning a value tuple to another variable, passing it as an argument or returning it copies every element, and the two variables are independent afterwards: changing `copy.Tax` does not touch `quote.Tax`. `System.Tuple` is a **class**, so assignment copies a reference and both variables name one object. A `System.Tuple` is therefore an ordinary object allocation, while a value tuple is stored inline wherever it lives: in a local, a field or an array slot. The general rules for struct copies (a struct returned from a property is a copy, where struct data really lives) are covered in the lesson on copying versus sharing. For tuples, the short version is that a value tuple behaves like a pair of `int`s, not like an object. ## Mutable fields versus read-only properties The runtime source declares the elements of `ValueTuple<T1, T2>` as **public fields**: `public T1 Item1;`. A value tuple is therefore a *mutable* value type, and `quote.Tax = 21m;` compiles. `Tuple<T1, T2>` keeps its values in `private readonly` fields and exposes them through get-only properties, so `legacy.Item2 = 21m;` fails with error CS0200: "Property or indexer 'Tuple<decimal, decimal>.Item2' cannot be assigned to -- it is read only". The immutability is shallow: you cannot replace an element, but an element that is a mutable object can still change inside. ## Element names exist only on value tuples Value tuple syntax lets you name elements, as in `(decimal Net, decimal Tax)`. The names are compile-time aliases for `Item1` and `Item2`; `Item1` still works when a name exists. `System.Tuple` has no naming syntax at all, so callers read `Item1` and `Item2` forever, which is the main readability complaint against it. ## Equality: `==` versus `Equals` | | `ValueTuple` (C# tuple syntax) | `System.Tuple` | |---|---|---| | Kind | struct | class | | Elements | public mutable fields | read-only properties | | Element names | yes, at compile time | none | | `==` and `!=` | element by element (C# 7.3 and later) | reference comparison | | `Equals` | element by element through `EqualityComparer<T>.Default` | element by element through `EqualityComparer<object>.Default` | | Deconstruction | built into the language | through `TupleExtensions.Deconstruct` | | More than seven elements | nested through the `Rest` element | nested through the `Rest` property | Neither type declares an `operator ==`. For value tuples the compiler itself rewrites `t1 == t2` into a comparison of each pair of elements. For `System.Tuple`, `==` falls back to the reference comparison every class gets, so `Tuple.Create(1, 2) == Tuple.Create(1, 2)` is `false` while `Equals` on the same pair is `true`, a classic code-review catch. ## Converting and choosing 1. `TupleExtensions.ToValueTuple()` converts a `System.Tuple` to the matching value tuple, and `ToTuple()` goes the other way. 2. `TupleExtensions` also supplies `Deconstruct` extension methods for arities 1 to 21, so `var (net, tax) = legacy;` works on a `System.Tuple`. 3. Prefer value tuples in new private and internal code: no object per tuple, element names, and language support for equality and deconstruction. 4. Keep `System.Tuple` where an existing API already exposes it. Switching a public signature from one to the other is a breaking change, because they are different types. For public APIs, Microsoft's tuple reference page suggests considering a class or struct instead of either tuple, since a named type documents itself. The snippet below shows the copy, the mutable field, the read-only property and the two equality behaviours side by side. ```csharp (decimal Net, decimal Tax) quote = (100m, 20m); var copy = quote; // copied: a separate value copy.Tax = 21m; // allowed: a public field var legacy = Tuple.Create(100m, 20m); Console.WriteLine(legacy == Tuple.Create(100m, 20m)); // False Console.WriteLine(legacy.Equals(Tuple.Create(100m, 20m))); // True ```

  • Can a C# value tuple hold more than seven elements?
    Yes. `ValueTuple` has generic versions up to eight type parameters, and the eighth, `TRest`, holds another tuple. The compiler nests automatically, so `(1, 2, 3, 4, 5, 6, 7, 8, 9).Item9` compiles and reads through `Rest`. A tuple that large is usually a sign that a named type is overdue.
  • Does `var (a, b) = Tuple.Create(1, 2);` compile in C#?
    Yes. `System.Tuple` has no `Deconstruct` instance method, but `TupleExtensions` in the `System` namespace declares `Deconstruct` extension methods for arities 1 to 21, and the compiler accepts an extension `Deconstruct` just like an instance one.
  • Is `System.Tuple` ever the better choice in new C# code?
    Rarely. You use it when an API you call or implement already exposes `System.Tuple`, or when several holders must share one immutable object by reference. Otherwise a value tuple is lighter for internal plumbing, and a named class, struct or record is clearer for anything a caller outside the type reads.

  • C# tuple syntax creates System.Tuple objects on the heap.
  • Value tuple elements are read-only, so a tuple value can never change.
  • Naming an element Net makes Item1 stop compiling.
  • == on two System.Tuple instances compares their elements.
  • Passing a value tuple to a method lets the method change the caller's copy.
open as a page

In C#, why does (a, b) = (b, a) swap two variables correctly when a = b; b = a; does not?

level: juniorimportance: should knowfreq 50%

basics

~10 s

(a, b) = (b, a) is a deconstructing assignment: C# reads both right-hand values before writing either target, so neither old value is lost. The two-statement version overwrites a before reading it back.

open as a page

How do you make a C# Point class support var (x, y) = point, and which rules does the compiler apply to Deconstruct?

level: middleimportance: should knowfreq 50%

basics

~20 s

Declare a void Deconstruct method with one out parameter per component, as an instance or extension method. The compiler calls it for var (x, y) = point and foreach (var (x, y) in points), choosing the overload by out-parameter count.

open as a page

A C# method returns (decimal Net, decimal Tax); why does assigning it to (decimal Tax, decimal Net) silently swap the values?

level: middleimportance: should knowfreq 40%

basics

~10 s

C# tuple element names are compile-time aliases for Item1 and Item2. Converting one tuple type to another matches elements by position, so the target's Tax receives the net amount, with no diagnostic.

open as a page

In C#, how does == compare two value tuples, and when can it disagree with ValueTuple.Equals?

level: middleimportance: should knowfreq 45%

basics

~10 s

Since C# 7.3 the compiler rewrites tuple == into element-by-element == comparisons, ignoring names. Equals uses EqualityComparer<T>.Default per element instead, so NaN or object-typed elements can make the two disagree.

open as a page

A C# pricing service returns (decimal Net, decimal Tax), yet System.Text.Json serializes the result as {}; why, and what is the fix?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

A C# tuple is a ValueTuple whose elements are fields named Item1 and Item2, and System.Text.Json skips fields by default. Net and Tax exist only in compiler metadata, so return a named record or class instead.

open as a page