C# 7.0 "deconstructor"

It's a part of the new tuple syntax - which has nothing to do with the Tuple<> classes - but is taking from functional programming.

Consider this class:

public class User
{
   public string Username { get; }
   public string FirstName { get; }
   public string LastName { get; }

   public User(string username, string firstName, string lastName)
   {
       // initialize properties
   }

   public void Deconstruct(out string username, out string firstName, out string lastName)
   {
       // initialize out parameters
   }
}

Usage:

var user = new User("foobaa", "foo", "baa");

Instead of

var username = user.Username;
var firstName = user.FirstName;
var lastName = user.LastName;

or

string username, firstName, lastName;
user.Deconstruct(out username, out firstName, out lastName);

You can write:

var (username, firstName, lastName) = user;

var fullName = $"{firstName} {lastName}";

Update


Another example that it might be used for, and this just speculations, I have not tried this, is together with pattern matching.

var users = new Dictionary<string, User>
{
    {"john", new User("jom", "John", "Malkovich") }
}

C# 6

User user;
users.TryGetValue("john", out user);

C# 7 pattern matching

users.TryGetValue("john", out User user);

C# 7 deconstruct

users.TryGetValue("john", out (username, firstname, lastname));    

Tags:

C#

C# 7.0