Do c# class deconstructors delete/destroy the class from memory?

129 views Asked by At

Im reading about c# 10 and read

"A deconstructor (also called a deconstructing method) acts as an approximate opposite to a constructor: whereas a constructor typically takes a set of values (as parameters) and assigns them to fields, a deconstructor does the reverse and assigns fields back to a set of variables."

I get that this can be used to get a bunch of member values in a class, but does it do anything regarding the life cycle of the class? As in does it force all references to it to be removed and for it to be garbage collected or does it just return values?

1

There are 1 answers

0
Dmitry Bychenko On BEST ANSWER

Deconstructor unlike Destructor (c# doesn't have them at all) doesn't do anything with memory allocation; deconstructor is just a syntactic sugar, it usually assigns out parameters and nothing more e.g.

    public class MyClass {
      public MyClass(int a, int b, int c) {
        A = a;
        B = b;
        C = c;
      }

      public int A { get; }

      public int B { get; }

      public int C { get; }

      // Deconstructor does nothing but assigns out parameters
      public void Deconstruct(out int a, out int b, out int c) {
        a = A;
        b = B;
        c = C;
      }
    }

then you can put

    MyClass test = new MyClass(1, 2, 3);

    ...

    // Deconstructor makes code easier to read
    (int a, int b, int c) = test;

instead of

    MyClass test = new MyClass(1, 2, 3);

    ...

    int a = test.A;
    int b = test.B;
    int c = test.C;