Quantcast
Viewing all articles
Browse latest Browse all 42

Deconstruction in C#7.0

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

Image may be NSFW.
Clik here to view.
image

Image may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
image

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

Image may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
image


Viewing all articles
Browse latest Browse all 42

Trending Articles