DEV Community

Alex Dhaenens
Alex Dhaenens

Posted on

What the hell is object deconstructing?

Remember last time I found a handy feature of C# 7.0? For those who don't, you can find my blogpost about it here. Well once again, I found something very interesting! It is called object deconstructing, and in short words, it is the same as destructuring in javascript (e.g. https://wesbos.com/destructuring-objects/), but in C#!

Just as in my post about pattern matching in C# 7.0, I'll be using the Elf class which has two properties: Age, which is the age and ElfishName, which is the elfish name of the elf.

What is it?

Object deconstructing makes it possible to do this:

static void DeconstructingElf(Elf elf)
        {
            (int age, string elfishName) = elf;

            Console.WriteLine($"Age: {age}");
            Console.WriteLine($"Name in elfish: {elfishName}");
        }
Enter fullscreen mode Exit fullscreen mode

Pretty cool right? You can extract properties from the object without actually accessing the properties by the get methods! What is even better, you can discard properties you don't need. You can do this with the discard operator (which is just a plain underscore) like this:

(int age, string _) = elf;
Enter fullscreen mode Exit fullscreen mode

What actually happens is that _ variables are discarded and thus can't be accessed. On a side note: you can use multiple discard operators in one deconstructing statement.

Enabling object deconstructing

There is a catch however: object deconstructing does not come out of the box. On the bright side, you only need to implement one method to be able to deconstruct objects of a specific type. This is how you do it:

public void Deconstruct(out int age, out string elfishName)
        {
            age = Age;
            elfishName = ElfishName;
        }
Enter fullscreen mode Exit fullscreen mode

This method is called the deconstructor which is always named Deconstruct and always returns void. The parameters are all out variables which, inside the method, you assign values to. When actually deconstructing, the values that are returned are always in the order you coded (in the Deconstruct method). So in this case the first variable is an int (the age) and the second a string (the elfishName.

The actual usage of deconstructing depends on your personal style (and the one of the company you are working for). I do like it but, I don't use it. This is because you need the deconstructor.

Sources

https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct
Demo project: https://bitbucket.org/aldhaenens/p-d-demo/src/master/

Top comments (2)

Collapse
 
saint4eva profile image
saint4eva

I love this feature.

Collapse
 
madza profile image
Madza

yup, comes in pretty handy ;)