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 to destructuring in other languages.
Only tuples C# 7.0 are deconstructed automatically. Other types need a Deconstruct method with out parameters, defined either directly on the type or as an extension method C# 3.0. Some .NET types such as KeyValuePair<TKey, TValue> and DictionaryEntry already provide one.
Code
csharp
void ProcessShipment(Shipment shipment)
{
var (tracking, country, postCode) = shipment;
// ...
}
class Shipment
{
public string Tracking { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
public void Deconstruct(out string tracking, out string country, out string postCode)
{
tracking = Tracking;
country = Country;
postCode = PostCode;
}
}csharp
void ProcessShipment(Shipment shipment)
{
var tracking = shipment.Tracking;
var country = shipment.Country;
var postCode = shipment.PostCode;
// ...
}Notes
- You can either:
- Use the
varkeyword to infer all the types from the deconstruction - Declare the types inline with the deconstruction individually
(string tracking, string country, var postCode) = shipment; - Assign the values directly to existing variables
(tracking, country, postCode) = shipment;
- Use the
- Use discards C# 7.0 for values you don't need, e.g.
var (_, country, _) = shipment; - Declaration and assignment can be mixed in the same deconstruction from C# 10.0
- Records C# 9.0 with positional parameters generate a
Deconstructmethod for you