I have the class Person
:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public void Deconstruct(out int id) { id = Id; }
}
And when I tried to deconstruct it with the following code:
var (id) = new Person();
The compiler says:
Cannot infer the type of implicitly-typed deconstructor variable 'id'.
The compiler doesn't say it when there are more than one parameters. Like this:
public void Deconstruct(out int id, out string name) { id = Id; name = Name; }
var (id, name) = new Person();
Deconstruction requires at least two variables to deconstruct to.
Otherwise, the expression (id) = new Person()
would be ambiguous between normal assignment and deconstructing assignment.
You can also see this from the other compiler error your code gives: Syntax error, ',' expected
.
This is a duplicate of this question
Deconstructions into a single element are not supported in C# 7.0.
It is unclear why you would need such a mechanism, as you can simply access a property or write a conversion operator to achieve the same thing.
Conceptually, a tuple of one element is just that one element (you don't need a tuple to hold it). So there is no tuple syntax (using parentheses notation) to facilitate that (not to mention it would be syntactically ambiguous). The same applies for deconstructions.
Here are the most relevant LDM notes I could find: 2017-03-15 (zero and one element tuples and deconstructions).
It is possible that such deconstruction could become allowed in some future recursive pattern scenarios, but that has not been finalized yet.
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