Using Deconstructors in C# 7.0

This is another awesome feature that got introduced with C# 7.0 which can be helpful in many scenarios while consuming various objects. Deconstruction is mostly discussed with another new feature System.ValueTuple but it can be used with other custom type as well. I have also discussed it in briefly in ValueTuple post at the link below. I will advise to go through that first before starting here.

How to use the new ValueTuples : A C# 7.0 feature

What is Deconstruction

It is a process of splitting an instance’s (value types and reference types) value into multiple parts and assigning them to new variables. Like, I mentioned that it is extremely useful with the Tuples which contains a set of values but can be used with other types.

How to use Deconstruction

We can leverage it in our custom classes, structs or interfaces. We need to implement Deconstruct method, which returns void and each deconstructed value should be added as out parameter in the method signature. We can have multiple overridden Deconstruct method based on the requirement. Let’s see an example

public class Person
{
    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

    public Person(string fName, string mName, string lName, int age)
    {
        FirstName = fName;
        MiddleName = mName;
        LastName = lName;
        Age = age;
    }
    public void Deconstruct(out string fName, out string lName)
    {
        fName = FirstName;
        lName = LastName;
    }

    public void Deconstruct(out string fName, out string lName, out int age)
    {
        fName = FirstName;
        lName = LastName;
        age = Age;
    }
}

Here we can see that I have provided two Deconstruct methods, one with two out parameters: fName, lName and other with three : fName, lName, age.

Person p = new Person("Brij", "Bhushan", "Mishra", 32);

//(string firstName, string lastName) = p;
// OR
var (firstName, lastName) = p;

Console.WriteLine($"Person Details: First Name: {firstName}, Last Name: {lastName}");


(string firstName, string lastName, int age) = p;

Console.WriteLine($"Person Details: First Name: {firstName}, Last Name: {lastName}, Age: {age}");

Here I created the instance of Person with all the details. Then in first deconstruction, we got the first name and last name which calls the first Deconstruct method of the class which has two out parameters. Note that we have two ways of deconstruction. First we explicitly declare the type of each field inside parentheses (commented out) and another, using var keyword so that C# infers the type of each variable. Similarly later, second Deconstruct method is called which deconstructs it in three variables. It can be really useful when we have a class with numerous properties, fields and most of the time, we need only few there we can use the Deconstruct methods.

Similar to ValueTuples, we can use discards here as well. To discard a variable of Deconstruct method, we can use underscore (_) as

Person p = new Person("Brij", "Bhushan", "Mishra", 32);
(string firstName, _ , int age) = p;

Console.WriteLine($"Hello {firstName}, your age is {age}");

Deconstruction use Extension method

There could be scenarios where you want to this feature but its an existing class where changes are not possible (like some third party classes, classes own by different team or even framework classes), there we can add this as an extension method. Lets assume that Person class doesn’t have Deconstruct methods and we can add it as an extension method as

public static class DeconstructionExtensions
{
    public static void Deconstruct( this Person p, out string fName, out string lName, out int age)
    {
        fName = p.FirstName;
        lName = p.LastName;
        age = p.Age;
    }
}

It will work in the same way as earlier.

Hope you have enjoyed the post and will be able to use in your day to day coding.

Thanks
Brij

Advertisements

2 thoughts on “Using Deconstructors in C# 7.0

  1. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #2548

  2. Pingback: Expression-bodied Members in C# | Code Wala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s