Search code examples
c#.netvaluetuple

Deconstruct tuple from ref variable


I have the folloving method.

private ref (int, int) GetValue()
{
  var array = new (int, int)[1];
  return ref array[0];
}

The following code works fine:

var (s1, s2) = GetValue();

But i need to use the ref feature. The following code also works:

ref var r = ref GetValue();

Now i want to deconstruct the tuple. The following code won't compile:

ref var (r1, r2) = ref GetValue();

Is it possible to deconstruct ref variable?


Solution

  • I haven't used ref value tuples yet, but in my understanding, not the contents of the tuple is ref, but the tuple itself. Therefore you need to specify an identifier, just as with ref arguments on a method for example.

    Deconstructing the value tuple would mean the ref in your call is useless. The variables itself don't get updated with the ref tuple any more.

    That would mean it makes perfectly sense to not allow this construction, and it doesn't seem possible to do so.