Deconstruction is a process of splitting a variable value into parts and storing them into new variables. This could be useful when a variable stores multiple values such as a tuple.
Let’s take a look at the code sample in Listing 1. In this code, method GetATuple returns a tuple with three values.
-
- (string name, string title, long year) GetATuple(long id)
- {
- string name = string.Empty;
- string title = string.Empty;
- long year = 0;
- if (id == 1000)
- {
- name = "Mahesh Chand";
- title = "ADO.NET Programming";
- year = 2003;
- }
-
-
- return (name, title, year);
-
- }
Listing 1.
The code snippet in Listing 2 calls the GetATuple method and displays the return values on the console.
- (string authorName, string bookTitle, long pubYear)
- = GetATuple(1000);
- Console.WriteLine("Author: {0} Book: {1} Year: {2}", authorName, bookTitle, pubYear);
Listing 2.
The code in Listing 2 can be deconstructed as the code in Listing 3, where three var types are used to store the return values.
- (var authorName, var bookTitle, var pubYear) = GetATuple(1000);
- Console.WriteLine("Author: {0} Book: {1} Year: {2}", authorName, bookTitle, pubYear);
Listing 3.
The code in Listing 3 can also be replaced by the following syntax in Listing 4.
- var (authorName, bookTitle, pubYear) = GetATuple(1000);
- Console.WriteLine("Author: {0} Book: {1} Year: {2}", authorName, bookTitle, pubYear);
Listing 4.
Summary
In this article, we learned the deconstruction process introduced in C# 7.0.
References
References used to write this article,
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/