Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuples and unpacking assignment support in C#?

Tags:

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

like image 919
jb. Avatar asked Dec 15 '11 03:12

jb.


People also ask

What is the difference between unpacking tuple and tuple assignment give example for each?

Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.

What is the unpacking of tuple explain with example?

Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments. THis act of mapping together is known as unpacking of a tuple of values into a norml variable. WHereas in packing, we put values into a regular tuple by means of regular assignment.

What is a tuple assignment?

Tuple Assignment (Unpacking) Unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.

Is unpacking possible in a tuple?

Unpacking a Tuple Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.


2 Answers

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 
like image 76
Elazar Avatar answered Nov 06 '22 00:11

Elazar


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 
like image 24
dtb Avatar answered Nov 05 '22 22:11

dtb