C# - Deconstructor

Dev_NarenDev_Naren
2 min read

These are newly introduced in C# 7.0 which can also be used to provide access to the values or expose the values associated with a class to the outside environment, apart from public fields, properties, and indexers. Deconstructor is a special method with the name “Deconstruct“ that is defined under the name to expose (Read only) the attributes of a class and this will be defined with a code that is reverse to a constructor.

To understand Deconstructor, we will add a code file in our project with the naming it as “TestTeacher.cs” and write the below code in it:

In the above case “Deconstruct1” (name cannot be changed) is a special method which will expose the attributes of Teacher class.We can capture the values exposed by “Deconstructors” by using Tuples, through the instance of class we have created.

We can even capture the values as below:

E.g (var id2, var Name2,var Subject2, var Designation2, var Salary2) = obj;

The above state can be implemented as following also:

E.g. var (id2, Name2, Subject2, Designation2, Salary2) = obj;

Now you print the above values as below and to test that add the below code in the Main method of “TestTeacher” class just above the ReadLine method.

Note : Deconstructor will provide read-only access to the attributes of a class.

We can also overload Deconstructors to access specific values from the list of attributes and to test that add the following Deconstructor in the Teacher class.

Now we can capture only those 3 values and to test that add the above code in the Main method of “TestTeacher” class just above the ReadLine method.

Without overloading the Deconstructors we can also access required attribute values by just putting “_” at the place whose values we don’t want to access, and to test this Add the below code in the Main method of TestTeacher class just above the ReadLine method.

So by Compiling above code our output will be like this…:-

0
Subscribe to my newsletter

Read articles from Dev_Naren directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dev_Naren
Dev_Naren

I am a software developer. Exploring tech world. I just post my thoughts about tech and anythings which I'm curious about.