There is a method that receives a ValueTuple
and returns it after modifying it. In this case, can I specify the field name of the ValueTuple
in the method parameter?
private static void Operation()
{
var tuple = (X: 10, Y: 20);
var changeTuple = ChangeTuple(tuple);
}
private static ValueTuple<int, int> ChangeTuple(ValueTuple<int, int> tuple)
{
tuple.Item1 = 100; // ex) tuple.X = 100;
tuple.Item2 = 200; // ex) tuple.Y = 200;
return tuple;
}
CodePudding user response:
Yes, you can simply replace ValueTuple<int, int>
to (int X, int Y)
:
private static (int X, int Y) ChangeTuple((int X, int Y) tuple)
{
tuple.X = 100;
tuple.Y = 200;
return tuple;
}
For reference: naming tuple's fields
Or you can use deconstruction:
private static (int X, int Y) ChangeTuple(ValueTuple<int, int> tuple)
{
var (X, Y) = tuple;
X = 100;
Y = 200;
return (X, Y);
}
Please note that in both cases you are not modifying the original ValueTuple
rather create a new one:
- In the first case it is because the
ValueTuple
is astruct
, so it is passed by value - In the second case we explicitly create a new named
ValueTuple