Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you destructure to a tuple with only one value?

In C# 7, it's apparently not possible to destructure to a tuple with only one item.

ValueTuple<T1> exists, so it's not because of that.

And backwards compatibility means a Deconstruct method with one argument must also be legal:

public void Deconstruct(out int i)

So why couldn't you write:

var (num) = foo;

Is it simply that there's no sensible use case for this?

like image 402
Drew Noakes Avatar asked Nov 20 '16 23:11

Drew Noakes


People also ask

What is deconstruction in c#?

C# deconstruction is a process of deconstruct instance of a class. It is helpful when we want to reinitialize object of a class. Make sure all the parameters of deconstructor are out type.


1 Answers

My guess: consider the following case:

int num;
(num) = foo;

If foo defines a deconstructor with out int and an implicit int cast operator, it will be ambiguous which should be invoked in this case

It is possible to have a compile error in this specific case while allowing the general case I guess, but since, as you mentioned, there is no use case and the syntax would be confusing, maybe it makes sense to not allow it at all

like image 63
KMoussa Avatar answered Oct 10 '22 02:10

KMoussa