CSharp - Type Creation Deconstructors

Introduction

A deconstructor assigns fields back to a set of variables.

A deconstruction method must be called Deconstruct, and have one or more out parameters.

The following code create a Rectangle class with Deconstruct method

class Rectangle
{
     public readonly float Width, Height;

     public Rectangle (float width, float height)
     {
         Width = width;
         Height = height;
     }

     public void Deconstruct (out float width, out float height)
     {
         width = Width;
         height = Height;
     }
}

To call the deconstructor:

var rect = new Rectangle (3, 4);
(float width, float height) = rect;          // Deconstruction
Console.WriteLine (width + " " + height);    // 3 4

The second line is the deconstructing call which is equivalent to the following:

float width, height;
rect.Deconstruct (out width, out height);

Or:

rect.Deconstruct (out var width, out var height);

Deconstructing calls allow implicit typing:

(var width, var height) = rect;

Or simply:

var (width, height) = rect;

If the variables into which you're deconstructing are already defined, omit the types:

float width, height;
(width, height) = rect;

This is called a deconstructing assignment.

You can overload the Deconstruct method and return different value to caller.

Demo

using System;
class MainClass// w ww  . ja va 2 s  .c  o m
{
   public static void Main(string[] args)
   {

        var rect = new Rectangle (3, 4);
        (float width, float height) = rect;          // Deconstruction
        Console.WriteLine (width + " " + height);    // 3 4

   }
}
class Rectangle
{
     public readonly float Width, Height;

     public Rectangle (float width, float height)
     {
         Width = width;
         Height = height;
     }

     public void Deconstruct (out float width, out float height)
     {
         width = Width;
         height = Height;
     }
}

Result