Deconstruction is a syntax to split a value into multiple parts and store those parts individually into new variables. For example, tuples that return multiple values. Let us take the following method as an example, which returns a tuple of two string variables, Title and Author (see the New changes to tuples section):
public (string Title, string Author) GetBookDetails()
{
return (Title: "Mastering Visual Studio 2017", Author: "Kunal Chowdhury");
}
Now, when you call the method GetBookDetails(), it will return a tuple. You can access its elements by calling the element name, as follows:
In a deconstructing declaration, you can split the tuple into parts and assign them directly into new variables. You can then access those variables individually, just like a local variable:
Until now, we have learned how to write the syntax to deconstruct a tuple. In C# 7.0, it's not limited to tuples only. You can use deconstructing assignments for any type, as long as it has a Deconstruct method in the following form: public void Deconstruct (out T1 x1, ..., out Tn xn) { ... }.
A Deconstruct method should use out parameters to return the values instead of using tuples. This is to enable you to have multiple overloads for different numbers of values.
For example, let us create a class named Book exposing the Deconstruct method with two out variables:
public class Book
{
public void Deconstruct (out string Title, out string Author)
{
Title = "Mastering Visual Studio 2017";
Author = "Kunal Chowdhury";
}
}
As we didn't expose any properties to access the values of Title and Author from the Book class, we will not find them generally in the IntelliSense popup when trying to access an instance of the class. Refer to the following screenshot:
As we have declared the Deconstruct method in the class, you can directly deconstruct the instance into multiple variables to get the desired output of the return values:
var book = new Book();
var (title, author) = book; //var (title, author) = new Book();
Console.WriteLine("Title : " + title);
Console.WriteLine("Author : " + author);
When you run the preceding code, you will get the following output in the console window: