Tuples and unpacking assignment support in C#?
C# is a strongly-typed language with a type system that enforces a rule that functions can have either none (void
) or 1 return value. C# 4.0 introduces the Tuple class:
Tuple<int, int> MyMethod()
{
return Tuple.Create(0, 1);
}
// Usage:
var myTuple = MyMethod();
var row = myTuple.Item1; // value of 0
var col = myTuple.Item2; // value of 1
There's a set of Tuple classes in .NET:
Tuple<int, int> MyMethod()
{
// some work to find row and col
return Tuple.Create(row, col);
}
But there's no compact syntax for unpacking them like in Python:
Tuple<int, int> coords = MyMethod();
mylist[coords.Item1][coords.Item2] //do work on this element
For .NET 4.7 and later, you can pack and unpack a ValueTuple
:
(int, int) MyMethod()
{
return (row, col);
}
(int row, int col) = MyMethod();
// mylist[row][col]
For .NET 4.6.2 and earlier, you should install System.ValueTuple:
PM> Install-Package System.ValueTuple
An extension might get it closer to Python tuple unpacking, not more efficient but more readable (and Pythonic):
public class Extensions
{
public static void UnpackTo<T1, T2>(this Tuple<T1, T2> t, out T1 v1, out T2 v2)
{
v1 = t.Item1;
v2 = t.Item2;
}
}
Tuple<int, int> MyMethod()
{
// some work to find row and col
return Tuple.Create(row, col);
}
int row, col;
MyMethod().UnpackTo(out row, out col);
mylist[row][col]; // do work on this element