In Python I can write
def myMethod():
#some work to find the row and col
return (row, col)
row, col = myMethod()
mylist[row][col] # do work on this element
But in C# I find myself writing out
int[] MyMethod()
{
// some work to find row and col
return new int[] { row, col }
}
int[] coords = MyMethod();
mylist[coords[0]][coords[1]] //do work on this element
The Pythonic way is obivously much cleaner. Is there a way to do this in C#?
Since C# 7, you can install System.ValueTuple:
Then you can pack and unpack a
ValueTuple
:There's a set of Tuple classes in .NET:
But there's no compact syntax for unpacking them like in Python:
An extension might get it closer to Python tuple unpacking, not more efficient but more readable (and Pythonic):
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:Here is a zip example with value unpacking. Here zip returns an iterator over tuples.
Output: