Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a deconstruction cannot mix declarations and expressions on the left

Tags:

c#

tuples

I have this code:

public static (int a, int b) f12()
{
    return (1, 2);
}

public static void test()
{
    int a;
    (a, int b) = f12(); //here is the error
}

When I try to compile it I get an error:

A deconstruction cannot mix declarations and expressions on the left

I don't understand why. Any suggestions?

like image 721
G. Lari Avatar asked Sep 06 '17 16:09

G. Lari


2 Answers

Update:

As OfirD points out, This feature was added to C# 10 .


Original Answer:

When I try to compile it I get an error:

A deconstruction cannot mix declarations and expressions on the left I don't understand why.

As Eric said, the best place to get an answer to a "why" question is from the designers. Conveniently, the meeting notes for the C# design are actually posted publicly. So, we can actually answer such questions!

Quoting the meeting notes, the reason you cannot mix declarations and expressions:

[Supporting mixed declarations and expressions] was a late design change we didn't get to implementing.

As of now, adding this feature to a future versions of C# 7.X is under consideration.

Relevant links:

  • https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-02-21.md#mixing-fresh-and-existing-variables-in-deconstruction
  • https://github.com/dotnet/csharplang/issues/125 .
like image 158
Brian Avatar answered Nov 04 '22 11:11

Brian


This is a more precise answer to my question:

May lead to occasional confusion, as in M((int x, y) = e) (declaring y)? [...]

Taken from Mixing fresh and existing variables in deconstruction mentioned by Brian's answer.

like image 35
G. Lari Avatar answered Nov 04 '22 11:11

G. Lari