Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7.0 "deconstructor"

Tags:

c#

c#-7.0

I'm reading about C# 7.0 new stuff, and I cannot grok, at least from the example given, what would be the usage for a "deconstructor".

Is it just syntactic sugar?

If someone could shed some light about it, that would be nice.

like image 846
David Brabant Avatar asked Dec 01 '16 08:12

David Brabant


Video Answer


1 Answers

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));    
like image 55
Michael Avatar answered Oct 20 '22 22:10

Michael