C # 7.0 "deconstructor"

I am reading about C # 7.0 new materials , and I can not understand, at least from the above example, what will be the use for the "deconstructor".

Is it just syntactic sugar?

If someone can shed light on this, it will be fine.

+4
source share
1 answer

This is part of the new tuple syntax that has nothing to do with the Tuple <> classes, but 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
   }
}

Using:

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

Instead

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 can be used for this, and this is just speculation, I have not tried this, along 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 Template Compatibility

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

C # 7 deconstruct

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

Source: https://habr.com/ru/post/1662509/


All Articles