What are the deconstructors?

Asked

Viewed 199 times

11

When studying about Records in C# 9 was filed the appeal Deconstruct() where the object is assigned to a Tuple. What is a Deconstruct()? Does it remove the reference of the object causing it to cease to exist? When to use it? What is the importance of using this resource?

  • Where did you see that? Does it have context? I don’t remember anything general about it. It even has a destructor, but not that.https://answall.com/q/9078/101

  • @Maniero I edited the question to be clear.

  • Then it’s something else entirely.

2 answers

12


There are some situations that you may want a particular object to be deconstructed with certain values assigned to variables.

To deconstruct is not to destroy. To build is to take parts and to make something become, and to destroy is to disappear with everything that exists. To deconstruct is to take this whole that was built at some point and go back to having separate parts.

You know in gastronomy when you say a certain food is out of control? Its parts are separated, for example, a hamburger where the bread is on the plate, next to the meat, and then the lettuce and tomato, etc. There is that kind of sandwich.

So to create an automatic mechanism that the compiler does the deconstruction when it needs to create an algorithm that determines which variables it will generate and how the values will be played on them. It is the opposite of the constructor that has variables that will be used to receive values and store in the object in specific fields.

And this was done by introducing a different concept than was used in C#. The mechanism used a form of Duck Typing, then if the compiler finds a method called Deconstruct() with one or more variables as parameters of type out, then the guy in question is able to do a deconstruction.

Taking the example of documentation:

using static System.Console;

public class Person {
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    public Person(string fname, string mname, string lname, string cityName, string stateName) {
        FirstName = fname;
        MiddleName = mname;
        LastName = lname;
        City = cityName;
        State = stateName;
    }

    public void Deconstruct(out string fname, out string lname) {
        fname = FirstName;
        lname = LastName;
    }

    public void Deconstruct(out string fname, out string mname, out string lname) {
        fname = FirstName;
        mname = MiddleName;
        lname = LastName;
    }

    public void Deconstruct(out string fname, out string lname, out string city, out string state) {
        fname = FirstName;
        lname = LastName;
        city = City;
        state = State;
    }
}

public class Example {
    public static void Main() {
        var p = new Person("John", "Quincy", "Adams", "Boston", "MA");
        var (fName, lName, city, state) = p; //essa sintaxe é de desconstrução chamando o terceiro método
        WriteLine($"Hello {fName} {lName} of {city}, {state}!");
        var (nome, sobrenome) = p; //aqui chama o primeiro método de desconstrução.
        WriteLine($"{nome} {sobrenome}");
        var (pnome, _, unome) = p; //aqui chama o segundo método de desconstrução.
        WriteLine($"{pnome} {unome}");
    }
}

Behold working in the ideone (will work when they update the compiler). And in the .NET Fiddle. Also put on the Github for future reference.

The first method you already know, is the constructor. The others are deconstructors. Note that you can have several since the signing be different. So the moment you deconstruct according to the amount of variables and their types, if you have, a different method will be called.

Notice that what the method does is to take the variables that will be deconstructed and are passed as out, that is, each variable is used to receive a value and not pass one. See link above how a parameter works out. So he does the processing that he has to do, in general he just takes a field and sends it to the parameter and this will send the value to the variable that he used in the deconstruction. Nothing prevents you from having other more complex processing, it is only required that all parameter variables are initialized there within the method.

The function of this method is only to process something in the object and to play the values to the one who asked, if it is within the established standards.

You can create those methods even as extension that the compiler can do the deconstruction.

I find it very good to make certain codes much shorter and reduce Boilerplate. And that’s the main advantage. Try taking out the deconstructors and writing the code from Main() that gives the same result, then tell me. Without it all works, but writes more code to access the data.

In some cases it may even eliminate getters, and just let it take object values in this way.

It is a reading feature, nothing is touched on the object (could even if wanted to do, but rare to be useful), reinforcement that it does not destroy anything.

If you’re curious how this is compiled, it would be something like this (only the second):

public static void Main() {
    Person p = new Person("John", "Quincy", "Adams", "Boston", "MA");
    string nome;
    string sobrenome;
    p.Deconstruct(out nome, out sobrenome);
    WriteLine(nome + " " + sobrenome);
}

Behold in the Sharplab how it really gets.

An important detail is that it was not assigned to a tuple. Syntax is a form of deconstruction of a tuple or other object that allows deconstruction. It looks like a tuple but it’s just a way to declare or use several variables that will receive values from deconstruction.

It has several features that if people learn to use could make codes shorter and expressive. It has a few tricks with cast that can help a lot too, but it’s another matter.

-1

Basically, what a constructor does is to create a new object of a certain type with certain parameters (here I am opting for the default constructor because it has no parameters).

So what the Deconstructor must do is deconstruct the object back to its original parts.

To be specific, you have the control to specify how you would like the object to be deconstructed.

source: http://www.macoratti.net/18/11/c_novers72.htm

  • 3

    This link may be a good suggestion, but your reply will not be valid if one day the link crashes. In addition, it is important for the community to have content right here on the site. It would be better to include more details in your response. A summary of the content of the link would be helpful enough! Learn more about it in this item of our Community FAQ: We want answers that contain only links?

  • 2

    Remembering that we also don’t want a copy-and-paste here in Stack Overflow. There may be quotes in your reply, but it’s important that it is your reply.

  • how so a reply Copied and pasted not worth?! Still would be a valid answer... Many answers here are Copied and pasted...

  • 2

    @Edumendonça I think the problem is to simply do a mere Ctrl-C Ctrl-V from elsewhere, without adding anything. A Help Center is very clear about this: "Don’t copy the full text from external sources; instead, use your words and ideas to support your own" - has also this discussion at the Meta

Browser other questions tagged

You are not signed in. Login or sign up in order to post.