Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deconstruct with one parameter not working [duplicate]

Tags:

c#

c#-7.0

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();
like image 346
Josbel Luna Avatar asked Dec 23 '22 14:12

Josbel Luna


2 Answers

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.

like image 173
SLaks Avatar answered Jan 05 '23 00:01

SLaks


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.

like image 45
Julien Couvreur Avatar answered Jan 05 '23 01:01

Julien Couvreur