Why can't you destroy a single-value tuple?

In C # 7, it apparently cannot destroy a tuple with only one element.

ValueTuple<T1> exists, so it is not because of this.

And backward compatibility means that the Deconstruct method with one argument should also be legal:

 public void Deconstruct(out int i) 

So why you could not write:

 var (num) = foo; 

Is it just that there is no reasonable use case for this?

+7
c # destructuring
source share
2 answers

My guess: consider the following case:

 int num; (num) = foo; 

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

In this particular case, a compilation error is possible, allowing in the general case to assume that, since you mentioned that it makes no sense to use and the syntax will be confusing, it may make sense to not allow it at all

+5
source share

I am working with Visual Studio 2017 RC. I found that Connect (); The link you provided is incorrect. The syntax of the example you specified compiles and works.

As a test, I used the following code:

 public class Foo { public int Bar { get; set; } public void Deconstruct(out int bar) { bar = Bar; } } var foo = new Foo { Bar = 3 }; var (num) = foo; //num is an int with a value of 3 var obj = foo; //obj is a Foo object with the same reference as foo 

In the above example, the variable num is an int with a value of 3. The variable obj is an object Foo with the same reference as Foo .

The following does not compile:

 (int num) = foo; (var num) = foo; //Both give error: The name `num` does not exist in the current context. 
+1
source share

All Articles