In C# 7.0 I can declare the following deconstructors for my class:
public class Customer
{
public string FirstName { get; }
public string LastName { get; }
public string Email { get; }
public Customer(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public void Deconstructor(out string firstName, out string lastName, out string company)
{
firstName = FirstName;
lastName = LastName;
company = "Nop-Templates";
}
public void Deconstructor(out string firstName, out string lastName)
{
firstName = FirstName;
lastName = LastName;
}
}
I suppose the idea of using our variables in the desconstructor instead of directly returning a tuple is so that you can have different overloads of the deconstructor. However, I do not seem to be able to deconstruct the object to three variables. I can only deconstruct it to two variables.
For example, this does not compile:
(string firstName, string lastName, string company) = customer;
And I get this error:
"Cannot deconstruct a tuple of '2' elements into '3' variables."
But this does and works:
(string firstName, string lastName) = customer;
What am I missing?
You have called your methods, Deconstructor
, rather than Deconstruct
. Also, you can't redeclare firstName
and lastName
in the two tuples. Make those change, and the following lines of code all compile just fine:
var customer = new Customer("a", "b");
(string firstName1, string lastName1, string company) = customer;
(string firstName2, string lastName2) = customer;
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