Skip to content

Deconstruction C# 7.0code reduction

A simple syntax for extracting tuple and property values from objects.

Many languages allow you to extract values from objects into variables. C# 7.0 introduces a new syntax for this called deconstruction which is similar in other ways.

This support is automatic for deconstructing from record and DictionaryEntry types however other types require a Deconstruct method to be defined either directly on the type or as an extension method C# 3.0.

Code

C#
void ProcessShipment(Shipment shipment)
{
    var (tracking, country, postCode) = shipment;

    // ...
}
C#
void ProcessShipment(Shipment shipment)
{
    var tracking = shipment.tracking;
    var country = shipment.Country;
    var postCode = shipment.PostCode;

    /// ...
}

Notes

  • You can either:
    • Use the var keyword to infer all the types from the deconstruction
    • Declare the types inline with the deconstruction individually (int tracking, string country, var postCode) = shipment;
    • Assign the values directly to existing variables (tracking, country, postCode) = shipment;
  • Declaration and assignment can be mixed in C# 10

More information