Deconstruction in C#7.0

Posted: July 29, 2017 in .NET, C#
Tags: , ,

In my earlier blog post related to Tuples, I had used the following two ways for accessing the elements of the tuple.

image

image

The first one is obviously inefficient and to be honest wrong, there is no point calling the method twice. The second one can be simplified further as shown in the snippet below:

image 

This is referred to as the deconstruction of the tuple.

This technique of deconstruction can be now applied to any . NET class/struct , by implementing the Deconstruct method.

image

The object instance can be then deconstructed back into three variables as shown below:

image

The code shown above is nothing but the syntactic sugar coat. The decompiled code clearly shows the Deconstruct method of the Person class getting invoked and the variables a , b & c does not exists in the complied code. These are replaced by variables declared with names same as the parameters of the Deconstruct method implementation.

image

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.