0
0
CsharpHow-ToBeginner · 3 min read

How to Use Deconstruct in C#: Simple Guide with Examples

In C#, deconstruct lets you unpack an object into separate variables using a Deconstruct method. You define this method in your class or struct, then use syntax like (var x, var y) = obj; to extract values simply.
📐

Syntax

The Deconstruct method is a special method you add to your class or struct. It usually looks like this:

  • public void Deconstruct(out Type1 var1, out Type2 var2, ...)
  • Inside, assign the object's fields or properties to the out parameters.
  • Then you can use (var1, var2, ...) = object; to unpack values.
csharp
public class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Deconstruct(out int x, out int y)
    {
        x = X;
        y = Y;
    }
}
💻

Example

This example shows how to define a Deconstruct method in a Point class and then unpack its values into variables.

csharp
using System;

public class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Deconstruct(out int x, out int y)
    {
        x = X;
        y = Y;
    }
}

class Program
{
    static void Main()
    {
        var point = new Point(5, 10);
        var (x, y) = point;  // Deconstruct here
        Console.WriteLine($"X: {x}, Y: {y}");
    }
}
Output
X: 5, Y: 10
⚠️

Common Pitfalls

Some common mistakes when using Deconstruct are:

  • Not defining the Deconstruct method with out parameters.
  • Trying to deconstruct an object without a Deconstruct method defined.
  • Using wrong variable types in the deconstruction pattern.

Always ensure your Deconstruct method matches the variables you want to unpack.

csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    // Wrong: Missing out keyword
    // public void Deconstruct(string name, int age) { ... }

    // Correct:
    public void Deconstruct(out string name, out int age)
    {
        name = Name;
        age = Age;
    }
}
📊

Quick Reference

ConceptDescription
Deconstruct methodA method with out parameters to unpack object values.
Syntax to use(var1, var2) = obj; unpacks values.
Out parametersMust be used in Deconstruct method to return values.
Matching variablesVariables on left must match Deconstruct out parameters in type and count.
Use casesSimplifies extracting multiple values from an object.

Key Takeaways

Define a public Deconstruct method with out parameters in your class or struct.
Use (var1, var2, ...) = object syntax to unpack values easily.
Ensure the Deconstruct method's out parameters match the variables you want to extract.
Without a Deconstruct method, you cannot use deconstruction syntax on your object.
Deconstruction improves code readability by unpacking multiple values in one line.