Desconstructors allows us to extract in a single expression, properties of an object or elements of a tuple, and assign them to distinct variables.
record
and record struct
automatically provide a Deconstruct
method.
Classes
before deconstruction we had to manually extract each variable
var pat = new Person() { Name = "Patrick", BirdDate = new DateOnly(1999, 1, 18)};
var name = pat.Name;
var birthDate = pat.BirthDate;
Console.WriteLine($"Name: {name}, birthdate: {birthDate}");
class Person
public class Person
{
public string Name { get; set; }
public string Location { get; set; }
}
with deconstruction
var pat = new Person() { Name = "Patrick", BirdDate = new DateOnly(1999, 1, 18)};
var (name, birthDate) = pat;
Console.WriteLine($"Name: {name}, birthdate: {birthDate}");
class Person with Deconstructor
public class Person
{
public string Name { get; set; }
public string Location { get; set; }
public void Deconstruct(out string name, out string location)
{
name = Name;
location = Location;
}
}
if you don’t want all properties, just discard some using the discard character _
var pat = new Person() { Name = "Patrick", BirdDate = new DateOnly(1999, 1, 18)};
var (name, _) = pat;
Console.WriteLine($"Name: {name}");
Tuples
The same applies to tuples
// tuple creation
(string name, string location) person = ("mario", "spain");
// deconstructor
var (name, location) = person;