SHARE:

Introducing C# 10: Mix declarations and expressions in a deconstruction

Introduction

Deconstructing an object in C# like JavaScript has been possible in C# for some time now. There are two syntaxes to achieve our ends: the first syntax which allows in a single line of code to declare and assign the variables that will contain the values of our deconstructed object. The second allows you to declare variables, to initialize them and then to assign them the values of the deconstructed object. The first syntax is the simplest but does not allow you to initialize the variables while the second allows it but in return you will write more than one line of code. C# 10 allows you to mix these two syntaxes, which was not the case before and that is what we will see in this article.

Reminder on deconstruction in C#

Deconstructing an object allows you to assign its properties to variables with the simplest syntax possible. To do this, you obviously have to implement a deconstructor. Let’s take the example of the Person class containing the FirstName and LastName properties, the deconstructor (public void Deconstruct) will look like this:

The two deconstruction syntaxes look like this:

Deconstruction in C# 10

C# 10 allow to mix these syntaxes, like this:

Prior C# 10 you’ll get this compilation error: Error CS8184 A deconstruction cannot mix declarations and expressions on the left-hand-side.

That’s all folks ! 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: