In my last blog post I discussed Tuple Types and how, in my opinion, they make scenario's such as returning multiple values from a method a lot easier than some of the previous alternatives.
In this post I'd like to introduce you to another new feature of C# 7.0 that goes hand in hand with Tuples, Deconstruction.
Deconstruction
Deconstruction is a way of breaking up a multifactor value into it's parts. In other words, it's a way of splitting a type into individual variables representing the values within the type. Reading both of these sentences is sort of giving me a bit of a headache so maybe it's best if I just give you an example.
Prior to the addition of deconstruction and borrowing from my last blog post, you might find yourself writing code like this:
public static (int, string) GetUser()
{
return (age: 35, name: "Joe");
}
var user = GetUser();
var age = user.age;
var name = user.name;
Using a new feature known as deconstruction declaration this same code would be written like this:
public static (int age, string name) GetUser()
{
return (35, "Joe");
}
(int age, string name) = GetUser();
This can also be rewritten to look like this:
public static (int, string) GetUser()
{
return (age: 35, name: "Joe");
}
var (age, name) = GetUser();
Using another new feature known as deconstruction assignment you can deconstruct a tuple assigning it's factors to existing variables.
public static (int, string) GetUser()
{
return (age: 35, name: "Joe");
}
int age;
string name;
(age, name) = GetUser();
You may have noticed that above I had said you could split a type into it's parts. The language designers have also hooked us up with the ability to use deconstruct a type. In order to accomplish this, the type need only declare a instance or extension method named deconstruct taking the following form:
class User
{
public int Age { get; }
public string Name { get; }
public User(int age, string name)
{
Age = age;
Name = name;
}
public void Deconstruct(out int age, out string name)
{
age = Age;
name = Name;
}
public static User GetUser()
{
return new User(35, "Joe");
}
}
var (age, name) = User.GetUser();
Conclusion
While I can't think of a scenario that's begging for this feature, in my opinion, deconstruction is a nice corollary to Tuples. The syntax is succinct which keeps inline with the code simplification goal of the language designers.