1

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?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Mufasatheking
  • 387
  • 2
  • 6
  • 16
  • 1
    You mention "class" in your question, are you actually talking about "objects"? – Progman Jun 18 '23 at 19:51
  • 3
    Are you confusing "deconstructors" and "destructors" (the latter better known as "finalizers")? – Joe Sewell Jun 18 '23 at 19:57
  • 3
    A deconstructor is a method like any other, except that it can be called implicitly with some syntactic sugar. It doesn't affect the lifetime of the object it's called on in the slightest. (And yes, objects and classes aren't the same thing, and C# has no destructors, though it confusingly uses the C++ destructor syntax for finalizers.) Note that finalizers themselves *also* do not affect the lifetime of an object except in obscure circumstances -- they are called as *part* of garbage collection, but otherwise garbage collection is automatic. – Jeroen Mostert Jun 18 '23 at 20:10

1 Answers1

5

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;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215