Destructuring
suggest changeDestructuring means unpacking a composite value (a tuple, an object, an array) into separate variables in a single statement. JavaScript, Python and Kotlin all have it, and so does C#, where the official name is deconstruction.
C# gives you two related tools:
- deconstruction:
var (name, age) = person;works on tuples and on any type that has aDeconstructmethod (records get one for free) - patterns: positional, property and list patterns pull values out of objects and arrays inside
isandswitch, and only bind them if the shape matches
This article covers both. Examples use C# 14 / .NET 10, but everything except list patterns (C# 11) and Index() (.NET 9) works since C# 7-10.
Deconstructing tuples
The simplest case is a tuple. Put the variable names in parentheses on the left side of =:
(string, int) GetPerson() => ("Alice", 30);
var (name, age) = GetPerson();
Console.WriteLine($"{name} is {age}");
Alice is 30
var (name, age) is shorthand for declaring each variable with an inferred type. You can also spell the types out, or mix var with explicit types:
(string name, int age) = GetPerson();
(var name2, int age2) = GetPerson();
Deconstruction is positional. Tuple element names are ignored, only order matters:
var size = (Width: 3, Height: 4);
var (h, w) = size; // h gets Width, w gets Height
Console.WriteLine($"h={h} w={w}");
h=3 w=4
The number of variables must match the number of tuple elements, otherwise you get a compile error:
var (x, y, z) = (1, 2);
// error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
Tuples are covered in depth in Language support for Tuples and Return multiple values from a method.
Assigning to existing variables
Without var or types, deconstruction assigns to variables that already exist:
string city;
int population;
(city, population) = ("Oslo", 709_000);
Console.WriteLine($"{city}: {population}");
Oslo: 709000
Since C# 10 you can mix new declarations and existing variables in one deconstruction:
int count = 0;
(count, var label) = (5, "items");
Console.WriteLine($"{count} {label}");
5 items
The targets can be anything assignable: fields, properties, array elements. This is common in constructors:
class Interval
{
public int Start { get; }
public int End { get; }
public Interval(int start, int end) => (Start, End) = (start, end);
}
Swapping values
The right-hand side is fully evaluated before anything is assigned, so swapping two variables doesn't need a temporary:
int x = 1, y = 2;
(x, y) = (y, x);
Console.WriteLine($"x={x} y={y}");
x=2 y=1
The same trick makes "update several values at once" loops read naturally. Fibonacci numbers:
int a = 0, b = 1;
for (int i = 0; i < 10; i++)
{
Console.Write($"{a} ");
(a, b) = (b, a + b);
}
Console.WriteLine();
0 1 1 2 3 5 8 13 21 34
It also works with array elements, which is handy in sorting algorithms: (arr[i], arr[j]) = (arr[j], arr[i]);.
The compiler turns tuple-to-tuple deconstruction like this into plain local assignments, no ValueTuple is allocated.
Discards
Use _ for values you don't need. A discard isn't a variable: you can use it any number of times and it never holds a value:
var (name, _) = GetPerson();
var (quotient, _) = Math.DivRem(17, 5);
var (_, remainder) = Math.DivRem(17, 5);
Console.WriteLine($"{quotient} r {remainder}");
3 r 2
Math.DivRem(int, int) returns a (int Quotient, int Remainder) tuple, so it can be deconstructed directly.
Nested deconstruction
Deconstruction patterns nest to match the shape of the value:
var ((first, last), (lat, lon)) = (("Ada", "Lovelace"), (51.5, -0.12));
Console.WriteLine($"{first} {last} at {lat}, {lon}");
Ada Lovelace at 51.5, -0.12
Deconstructing your own types with Deconstruct
Any type can be deconstructed if it has an accessible method named Deconstruct that returns void and has only out parameters. The compiler translates var (x, y) = point; into point.Deconstruct(out var x, out var y);.
class Point(int x, int y)
{
public int X { get; } = x;
public int Y { get; } = y;
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
var (px, py) = new Point(3, 4);
Console.WriteLine($"{px}, {py}");
3, 4
A compact way to write the body is to deconstruct a tuple into the out parameters:
public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
Several Deconstruct overloads
You can define several Deconstruct methods as long as they have different numbers of parameters. The compiler picks the one matching the number of variables:
class Color(byte r, byte g, byte b, byte a)
{
public byte R => r;
public byte G => g;
public byte B => b;
public byte A => a;
public void Deconstruct(out byte r, out byte g, out byte b) =>
(r, g, b) = (R, G, B);
public void Deconstruct(out byte r, out byte g, out byte b, out byte a) =>
(r, g, b, a) = (R, G, B, A);
}
var c = new Color(255, 128, 0, 200);
var (r, g, b) = c;
var (_, _, _, alpha) = c;
Console.WriteLine($"rgb({r}, {g}, {b}) alpha={alpha}");
rgb(255, 128, 0) alpha=200
Two overloads with the same number of parameters but different types compile, but using them with var is ambiguous and won't compile. Keep one Deconstruct per arity.
Deconstruct as an extension method
Deconstruct can also be an extension method, which lets you add deconstruction to types you don't own:
static class UriExtensions
{
public static void Deconstruct(this Uri uri,
out string scheme, out string host, out int port)
{
scheme = uri.Scheme;
host = uri.Host;
port = uri.Port;
}
}
var (scheme, host, port) = new Uri("https://example.com:8080/docs?q=1");
Console.WriteLine($"{scheme} {host} {port}");
https example.com 8080
Records deconstruct for free
Positional records (record, record struct) get a compiler-generated Deconstruct with one out parameter per primary-constructor parameter, in declaration order:
record Person(string First, string Last, int BirthYear);
var person = new Person("Grace", "Hopper", 1906);
var (first, last, born) = person;
Console.WriteLine($"{first} {last}, born {born}");
Grace Hopper, born 1906
Only the positional parameters are included. Properties you add in the record body are not part of Deconstruct.
Note that classes and structs with primary constructors (class Point(int x, int y)) do not get a generated Deconstruct; only records do.
Built-in types that support deconstruction
Several .NET types ship with Deconstruct:
// KeyValuePair<TKey, TValue>
var dict = new Dictionary<string, int> { ["apples"] = 3, ["pears"] = 5 };
foreach (var (fruit, qty) in dict)
Console.WriteLine($"{fruit}: {qty}");
// DateTime into DateOnly + TimeOnly (.NET 8+)
var (date, time) = new DateTime(2026, 10, 17, 14, 30, 0);
Console.WriteLine($"{date} | {time}");
// DateOnly into year, month, day (.NET 8+)
var (year, month, day) = new DateOnly(2026, 10, 17);
Console.WriteLine($"{year}-{month}-{day}");
// TimeOnly into hour, minute (.NET 8+)
var (hour, minute) = new TimeOnly(14, 30);
Console.WriteLine($"{hour}:{minute}");
// old-style System.Tuple, via extension methods in TupleExtensions
var (num, word) = Tuple.Create(1, "one");
Console.WriteLine($"{num} {word}");
apples: 3
pears: 5
10/17/2026 | 14:30
2026-10-17
14:30
1 one
DateTime also has a (year, month, day) overload, and TimeOnly has (hour, minute, second) and longer ones. DictionaryEntry (from non-generic Hashtable) deconstructs into (key, value) as well.
Deconstruction in foreach
As the dictionary example shows, the iteration variable of foreach can be a deconstruction. This pairs well with LINQ methods that return tuples:
string[] names = ["Ann", "Bob", "Cid"];
// Index() returns (int Index, T Item), .NET 9+
foreach (var (i, name) in names.Index())
Console.WriteLine($"{i}: {name}");
int[] nums = [1, 2, 3];
// Zip with two arguments returns (TFirst First, TSecond Second)
foreach (var (n, s) in nums.Zip(names))
Console.WriteLine($"{n} -> {s}");
0: Ann
1: Bob
2: Cid
1 -> Ann
2 -> Bob
3 -> Cid
Lambda parameters can't be deconstructed
Unlike JavaScript (([a, b]) => ...) or Kotlin ({ (a, b) -> ... }), C# has no deconstruction in lambda parameter lists:
var pairs = new[] { (1, "one"), (2, "two") };
pairs.Select(((n, w)) => $"{n}={w}");
// error CS1001: Identifier expected
Deconstruct inside the body, or just use the element names:
pairs.Select(p => { var (n, w) = p; return $"{n}={w}"; });
pairs.Select(p => $"{p.Item1}={p.Item2}");
Arrays: no direct deconstruction
var (a, b) = array; doesn't compile, because arrays have no Deconstruct method:
int[] arr = [1, 2];
var (a, b) = arr;
// error CS8129: No suitable 'Deconstruct' instance or extension method was found
// for type 'int[]', with 2 out parameters and a void return type.
There are two ways around that. You can write an extension method, but it must decide what to do when the length doesn't match, because deconstruction can't fail:
static class ArrayExtensions
{
public static void Deconstruct<T>(this T[] arr, out T first, out T second)
{
if (arr.Length != 2)
throw new ArgumentException($"expected 2 elements, got {arr.Length}");
(first, second) = (arr[0], arr[1]);
}
}
var (key, value) = "key=value".Split('=');
Console.WriteLine($"{key} / {value}");
key / value
The better option is usually a list pattern, described next, which checks the length and binds the elements in one step.
List patterns: destructuring arrays and lists
List patterns (C# 11) match arrays, lists, spans and any type with an indexer and a Length or Count. var sub-patterns bind elements to variables and .. matches any number of elements, optionally capturing them as a slice:
int[] arr = [10, 20, 30, 40];
if (arr is [var first, var second, .. var rest])
Console.WriteLine($"first={first} second={second} rest=[{string.Join(", ", rest)}]");
if (arr is [.., var last])
Console.WriteLine($"last={last}");
first=10 second=20 rest=[30, 40]
last=40
Because it's a pattern, the match simply fails when the shape is wrong. That makes it a safe replacement for the array Deconstruct above:
if ("host:8080".Split(':') is [var host, var portStr] && int.TryParse(portStr, out var port))
Console.WriteLine($"host={host} port={port}");
host=host port=8080
In a switch expression, list patterns make a neat little command parser:
static string Describe(string[] args) => args switch
{
[] => "no args",
["help"] => "showing help",
["add", var item] => $"adding {item}",
["add", var item, .. var more] => $"adding {item} and {more.Length} more",
[var cmd, ..] => $"unknown command {cmd}",
};
Console.WriteLine(Describe([]));
Console.WriteLine(Describe(["help"]));
Console.WriteLine(Describe(["add", "milk"]));
Console.WriteLine(Describe(["add", "milk", "eggs", "bread"]));
Console.WriteLine(Describe(["remove", "milk"]));
no args
showing help
adding milk
adding milk and 2 more
unknown command remove
Positional patterns
A positional pattern uses the same Deconstruct method (or tuple) as deconstruction, but inside is and switch. Each position can be a nested pattern: a constant, a relational pattern like > 0, var x, or a discard:
record Point(int X, int Y);
static string Quadrant(Point p) => p switch
{
(0, 0) => "origin",
(var x, 0) => $"on x axis at {x}",
(0, _) => "on y axis",
( > 0, > 0) => "Q1",
( < 0, > 0) => "Q2",
( < 0, < 0) => "Q3",
_ => "Q4",
};
Console.WriteLine(Quadrant(new Point(0, 0)));
Console.WriteLine(Quadrant(new Point(5, 0)));
Console.WriteLine(Quadrant(new Point(-1, 1)));
origin
on x axis at 5
Q2
Combined with a type test, a positional pattern checks the type, deconstructs and binds in one expression:
object o = new Point(2, 7);
if (o is Point(var a, var b) && a < b)
Console.WriteLine($"Point with a={a} < b={b}");
Point with a=2 < b=7
Switching on a tuple you build on the spot is a common way to branch on several values at once:
static string FizzBuzz(int n) => (n % 3, n % 5) switch
{
(0, 0) => "FizzBuzz",
(0, _) => "Fizz",
(_, 0) => "Buzz",
_ => n.ToString(),
};
Console.WriteLine(string.Join(" ", Enumerable.Range(1, 15).Select(FizzBuzz)));
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Property patterns: destructuring by name
Positional deconstruction depends on order. Property patterns pick values by name, which is closer to JavaScript's const { name, total } = order, and they work on any type, no Deconstruct needed:
record Customer(string Name, string Country);
record Order(int Id, Customer Customer, decimal Total);
var order = new Order(42, new Customer("Linus", "FI"), 99.5m);
if (order is { Customer: { Name: var name, Country: "FI" }, Total: var total })
Console.WriteLine($"{name} from Finland spent {total}");
// extended property pattern, C# 10
if (order is { Customer.Name: var customerName })
Console.WriteLine(customerName);
Linus from Finland spent 99.5
Linus
Note that a property pattern also checks for null: { } only matches a non-null value. See Pattern Matching for more on patterns.
Gotchas
- Null throws. Deconstructing a
nullreference callsDeconstructon it and throwsNullReferenceException. A positional pattern (if (p is (var x, var y))) doesn't throw, it just fails to match. - Order, not names.
var (height, width) = size;happily assignsWidthtoheight. When order is easy to get wrong, prefer property patterns or plain property access. - No partial deconstruction. You must provide a variable or
_for every element.var (a, b) = (1, 2, 3);is an error, writevar (a, b, _) = .... - Deconstruct must return void. A
Deconstructthat returnsbool(to signal failure) isn't used by the compiler. If deconstruction can fail, use a pattern or aTryXxx(out ...)method instead. - Types must line up. Each element is converted to the declared variable type with normal implicit conversions:
(long l, double d) = (1, 2);works,(int i, string s) = (1, 2);doesn't.