Skip to content
← Back to Blog

How to Deconstruct objects in C# like we do in Javascript

⏱️ 2 min read
c#javascriptdeconstructionsyntax.net
How to Deconstruct objects in C# like we do in Javascript

I've been using C# for about a decade now, and every now and again I discover something that surprises me. This week it's the ability to deconstruct as we do in Javascript (and I'm not talking about using Tuples!).

Below is a simple example of deconstruction taking place to draw out the power, and defence property for our Trex object,

1const trex = {
2    statistics: {
3        power: 10,
4        defence: 2
5    },
6    name: "T-Rex", 
7};
8
9const { power, defence } = trex.statistics;
10
11console.log(`Power ${power}, Defence ${defence}`);
12//Power 10, Defence 2
13
14//Better than doing:
15//const power = trex.statistics.power;
16//const defence = trex.statistics.defence;

As Mozilla's definition states,

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables - Destructuring assignment.

It's a powerful syntactical sugar, especially in the scenarios where you have a nested object with long names. As deconstruction can lead to cleaner, more readable code its uses are great on large object types. Now let's take a look at the same thing but in C#,

1namespace deconstruction
2{
3    public record Statistics(int Power, int Defence);
4
5    public class Trex
6    {
7        public Statistics Statistics;
8        public string Name;
9
10        public Trex()
11        {
12            Name = "T-Rex";
13            Statistics = new Statistics(10, 5);
14        }
15
16        // Return the first and last name.
17        public void Deconstruct(out int power, out int defence)
18        {
19            power = Statistics.Power;
20            defence = Statistics.Defence;
21        }
22    }
23}

Ok admittedly it's not as elegant as its Javascript counterpart as we need to define what we want to deconstruct upfront as well as have a function for each combination 😬! but it's still got its uses... check it out,

1using System;
2
3namespace deconstruction
4{
5    class Program
6    {
7        static void Main(string[] args)
8        {
9            var trex = new Trex();
10            var (power, defence) = trex;
11
12            Console.WriteLine($"Power: {power}, Defence: {defence}");
13            //Power: 10, Defence: 5
14
15            //Better than doing:
16            //var power = trex.statistics.power;
17            //var defence = trex.statistics.defence;
18        }
19    }
20}

Who knows what other hidden gems 💎 lie buried with the Microsoft docs!