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#?
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#?
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
Tuple
can 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 on C#: the tuple is a fundamental construct in many functional languages, and greatly assists in their static typing.
For functions you must return either 1 object or void
. But you can approach this problem several ways.
struct
or a class
that will contain a,b,c,d
and return that as your function e.g. data foo()
data will contain a,b,c,dout
keyword in the parameter of your function e.g. foo(out a, out b, out c, out d), but your variable inputs will need to be initialized. More info here. See http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspxref
which is similiar to out. See http://msdn.microsoft.com/en-US/library/14akc2c7(v=vs.80).aspxarrray
or a list
as another member has pointed outAlso remember depending on the type that you are passing strcut vs objects that you value may be passed as a Value
or Reference
. See http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx