skip to content

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%

answer

  1. a pattern, not an interface
  2. void with out parameters
  3. instance or extension method
  4. overloads must differ by count
  5. discards skip components

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.

solid answer

~50 s

Deconstruction is **pattern-based**: there is no interface to implement. For `var (x, y) = point;` the compiler looks for an accessible `Deconstruct` method, instance or **extension**, with two `out` parameters and a `void` return, and reports CS8129 if none fits. Each `out` parameter becomes one variable, so the same method powers `foreach (var (x, y) in route)`, discards such as `var (_, y) = point;`, and assignment into existing variables (mixing existing and new variables needs C# 10). You can declare several overloads, but they must differ by **arity**: two `Deconstruct` methods with two `out` parameters each make every two-variable deconstruction ambiguous (CS0121), even when the parameter types differ. An extension `Deconstruct` lets you deconstruct a type you don't own, and `KeyValuePair<TKey, TValue>`'s own `Deconstruct` is what makes `foreach (var (key, value) in dictionary)` work.

code

csharp · 34 lines
csharp
using System;
using System.Collections.Generic;

var route = new List<Point> { new(0, 0), new(3, 4), new(6, 8) };
foreach (var (x, y) in route)                 // calls Point.Deconstruct(out int, out int)
    Console.WriteLine($"{x},{y}");

var (_, lastY) = route[^1];                   // discard the X component
var (px, py, label) = route[1];               // picks the three-out-parameter overload
Console.WriteLine($"{lastY} {px + py} {label}");

var (host, port) = new Uri("https://example.com:8443/orders");  // extension Deconstruct
Console.WriteLine($"{host}:{port}");

class Point(int x, int y)
{
    public int X => x;
    public int Y => y;
    public void Deconstruct(out int x, out int y) { x = X; y = Y; }
    public void Deconstruct(out int x, out int y, out string label)
    {
        (x, y) = (X, Y);
        label = $"({X}, {Y})";
    }
}

static class UriDeconstruction
{
    public static void Deconstruct(this Uri uri, out string host, out int port)
    {
        host = uri.Host;
        port = uri.Port;
    }
}

go deeper

for a junior

Recall that var (x, y) = point calls a void Deconstruct method with two out parameters, and that _ discards a component.

for a middle

Explain the pattern lookup: instance or extension method, void return, overload chosen by arity, CS8129 when none fits, and CS0121 for same-arity overloads.

for a senior

Design Deconstruct overloads by arity, add extension methods for library types you cannot change, and keep instance and extension methods of the same arity from colliding.

for a principal

Judge when positional deconstruction aids readability on a type and when named properties should stay the only access path, since component order becomes part of the contract.

## Deconstruction is a compiler pattern A **deconstruction** splits one value into several variables in one statement: `var (x, y) = point;`. For tuples the language does this itself. For any other class, struct or interface, the compiler looks for a method by **name and shape**, not through an interface. That method is `Deconstruct`. The rules the compiler enforces for a deconstruction into *n* variables: - The method is named `Deconstruct` and is accessible at the call site. - It has exactly *n* `out` parameters, one per target. - It returns `void`. - It can be an **instance method** on the type or an **extension method** in a static class whose namespace is imported. When nothing fits, the compiler reports CS8129: "No suitable 'Deconstruct' instance or extension method was found for type 'Q', with 2 out parameters and a void return type." A method that returns `bool` or a tuple does not qualify. ## Writing one for `Point` ```csharp class Point(int x, int y) { public int X => x; public int Y => y; public void Deconstruct(out int x, out int y) { x = X; y = Y; } } ``` The compiler lowers `var (x, y) = point;` into declaring two locals and calling `point.Deconstruct(out x, out y)`. Deconstruction is ordinary method calling: nothing is allocated unless your method allocates, and each `out` value is a copy or a reference exactly as any `out` argument would be. ## Every form that uses it | Form | Example | Notes | |---|---|---| | Declaration with `var` | `var (x, y) = point;` | types come from the `out` parameters | | Explicit types | `(int x, int y) = point;` | each `out` value must convert to the declared type | | Discard | `var (_, y) = point;` | the component is still produced, then dropped | | Existing variables | `(px, py) = point;` | assigns locals, fields, array elements or properties | | Mixed existing and new | `(px, var py) = point;` | C# 10 and later; C# 9 reports CS8773 | | `foreach` | `foreach (var (x, y) in route)` | calls `Deconstruct` on each element | A discard does not let you skip arity: `var (_, y) = point;` still needs a two-parameter `Deconstruct`. ## Overloads and arity A type may offer several `Deconstruct` methods, typically to expose a different number of components: a two-component `(x, y)` and a three-component `(x, y, label)`. The compiler picks the overload by the number of targets. Two overloads with the **same number** of `out` parameters are a trap: 1. Declaring them compiles. 2. Every deconstruction with that arity then fails with CS0121, "The call is ambiguous between the following methods or properties", plus CS8130 for each `var` variable whose type could not be inferred. 3. Explicit target types do not rescue it: the .NET 10 SDK compiler reports the same CS0121 for `(int a, string b) = reading;` and for existing typed variables. So design overloads by arity, never by parameter types alone. ## Deconstructing types you don't own An extension method makes any type deconstructible: ```csharp static class UriDeconstruction { public static void Deconstruct(this Uri uri, out string host, out int port) { host = uri.Host; port = uri.Port; } } ``` The base class library uses both styles. `KeyValuePair<TKey, TValue>` declares an instance `Deconstruct(out TKey key, out TValue value)`, which is why `foreach (var (key, value) in prices)` works over a dictionary, and `TupleExtensions` supplies extension `Deconstruct` methods for `System.Tuple`. When a type has an instance `Deconstruct` and an imported extension `Deconstruct` of the same arity, the .NET 10 SDK compiler binds the **instance** method without any diagnostic, as for any other method call, so an extension written for a type that later gains its own `Deconstruct` silently stops being called. ## Where else your method is used - **Positional patterns** such as `point is (0, 0)` call the same `Deconstruct`; the pattern-matching lessons cover them. - **Positional records** get a compiler-generated `Deconstruct`; the records lessons cover what it includes. - **Out parameter rules** themselves, such as definite assignment, belong to the material on by-reference parameters. What stays here is the contract: one `void` method per arity, `out` parameters in component order, and no two overloads that a deconstruction of the same length could both match.

  • Does deconstructing a Point inside a hot C# loop allocate?
    Deconstruction itself does not: it is a call to `Deconstruct` that writes into locals through `out` parameters. Allocation comes only from what the method does, such as an overload that builds a label string, or from how the loop enumerates, never from the deconstruction syntax.
  • Why can't a C# Deconstruct method return a bool to signal failure?
    The compiler only binds a `Deconstruct` with a `void` return; any other return type gives CS8129. Deconstruction assumes every value can always be split. When splitting can fail, expose a `TryGet...` method or test with a pattern first.
  • What happens in C# when a type has an instance Deconstruct and an imported extension Deconstruct of the same arity?
    The instance method wins, exactly as with any method call: the compiler only looks at extension methods when no applicable instance method exists, and it reports nothing. An extension you wrote for a library type therefore stops being called, silently, once the library adds its own `Deconstruct` with that arity.

  • A type must implement an interface before it can be deconstructed.
  • Deconstruct returns a tuple holding the components.
  • Same-arity overloads are fine as long as the out parameter types differ.
  • Only types whose source you own can be deconstructed.
  • A discard lets you call a two-component Deconstruct with three targets.