Deconstruction In C#

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.

  1. // This method returns a tuple with three values  
  2. (string name, string title, long year) GetATuple(long id)  
  3. {  
  4. string name = string.Empty;  
  5. string title = string.Empty;  
  6. long year = 0;  
  7. if (id == 1000)  
  8. {  
  9. name = "Mahesh Chand";  
  10. title = "ADO.NET Programming";  
  11. year = 2003;  
  12. }  
  13. // tuple literal  
  14.   
  15. return (name, title, year);  
  16.   
  17. }   

Listing 1.

The code snippet in Listing 2 calls the GetATuple method and displays the return values on the console.

  1. (string authorName, string bookTitle, long pubYear)  
  2. = GetATuple(1000);  
  3. 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.

  1. (var authorName, var bookTitle, var pubYear) = GetATuple(1000);  
  2. 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.

  1. var (authorName, bookTitle, pubYear) = GetATuple(1000);    
  2. 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.

Next C# 7.0 Feature >>  Tuples 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/
Author
Mahesh Chand
1 269.3k 239.8m
Next » Pattern Matching In C#