Tuples and unpacking assignment support in C#?

jb. picture jb. · Dec 15, 2011 · Viewed 14.7k times · Source

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

Answer

Elazar picture Elazar · Aug 10, 2017

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