Posts Deconstructing Tuples in C# 7
Post
Cancel

Deconstructing Tuples in C# 7

We discussed Tuples in the previous post. They give an easy to use interface, when we need only a subset of members from the class using a single function. But, what if we need to make it more implicit, without having to call a function. C#, now offers the Deconstruct function.  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 public class Person 
 {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public void Deconstruct(out string firstName, out string lastName)
        {
            firstName = FirstName;
            lastName = LastName;
        }
}

var person = new Person
{
     FirstName = "John",
     LastName = "Doe",
     Age = 20,
     EmailId = "john.doe@example.com"                
};

(var firstName, var lastName) = person;

Assert.Equal("John", firstName);
Assert.Equal("Doe", lastName);

Here, since the Person class, offers the Deconstruct function with 2 variables, the object of Person class (person), can be implicitly converted to a tuple value. I believe, people who like using implicit and explicit operator would appreciate this.
Please find a sample implementation at GitHub.
References : Microsoft Docs

This post is licensed under CC BY 4.0 by the author.