Josbel Luna Josbel Luna - 2 months ago 15
C# Question

Deconstruct with one parameter not working

I have the class


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();

Answer Source

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.