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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With