How to assign a list of variables in one expression

Perl has the ability to:

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

where foo returns 4 variables rather than assigning them one at a time. Is there something similar in C #?

+7
c # perl
source share
3 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 
+8
source share

Tuple may be a useful construct for this.

 public Tuple<int, string, double> Foo() { ... } 

Then you can do:

 var result = Foo(); int a = result.Item1; string b = result.Item2; double c = result.Item3; 

This is a legacy of the increasing influence of functional programming styles in C #: a tuple is a fundamental construct in many functional languages ​​and greatly helps in their static typing.

+2
source share

For functions, you must return either a single object or void . But you can address this problem in several ways.

  • You can create a data structure, such as a struct or class , that will contain a,b,c,d and return it as your function, for example. data foo() data will contain a, b, c, d
  • You can use the out keyword in the parameter of your function, for example. foo (out a, out b, out c, out d), but your variable inputs must be initialized. More info here. See http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
  • You can also use ref , which is similar. See http://msdn.microsoft.com/en-US/library/14akc2c7(v=vs.80).aspx
  • Or, if a, b, c, d are the same, you can return them as a collection as arrray or list , as another member pointed out

Also remember that depending on the type you pass strcut vs, the objects you evaluate may be passed as Value or Reference . See http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx

+1
source share

All Articles