Search code examples
c#tuplesiterable-unpackingdecomposition

Tuples and unpacking assignment support in C#?


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#?


Solution

  • 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