Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign to a list of variables in one statement

Tags:

c#

perl

Perl has the ability to do:

my ($a,$b,$c,$d) = foo(); 

where foo returns 4 variables, as opposed to assigning it one at a time. Is there something similar in C#?

like image 334
user2521358 Avatar asked Jul 29 '13 13:07

user2521358


People also ask

How do you assign a list to a variable in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.

How do you assign multiple values to one variable in Java?

You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .

Can you declare and initialize multiple variables with a single expression?

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.


1 Answers

No, basically. Options:

object[] values = foo();
int a = (int)values[0];
string b = (string)values[1];
// etc

or:

var result = foo();
// then access result.Something, result.SomethingElse etc

or:

int a;
string b;
float c; // using different types to show worst case
var d = foo(out a, out b, out c); // THIS WILL CONFUSE PEOPLE and is not a 
                                  // recommendation
like image 53
Marc Gravell Avatar answered Sep 21 '22 21:09

Marc Gravell