Can we write a method which returns multiple values?
Method returning multiple values?
Collapse
This topic is closed.
X
X
-
satyanarayan sahooTags: None -
Marc Gravell
Re: Method returning multiple values?
Can we write a method which returns multiple values?
Well, it can only have one true return...
If all the values are of the same type, you could return an
array/list/etc - although it doesn't give much indication of what is at
each index.
Alternatively, "out" can be used to achieve the same effect as multiple
return values, but it is a little confusing to some devs, so it isn't
very common (except for in "bool Try{...}(..., out value)" scenarios).
Finally, yout could return a "tuple" - something with multiple values.
Examples of all 3 below.
Marc
static class Program
{
static void Main()
{
int[] vals = MultipleViaArra y();
int a = vals[0], b = vals[1];
// or...
a = MultipleViaOut( out b);
// or...
var tuple = MultipleViaTupl e();
a = tuple.Value1;
b = tuple.Value2;
}
static int[] MultipleViaArra y()
{
return new int[] { 5, 7 };
}
static int MultipleViaOut( out int otherValue)
{
otherValue = 5;
return 7;
}
static Tuple<int, intMultipleViaT uple()
{
return new Tuple<int, int>(5, 7);
}
}
class Tuple<TValue1, TValue2>
{
public TValue1 Value1 { get; private set; }
public TValue2 Value2 { get; private set; }
public Tuple(TValue1 value1, TValue2 value2)
{
Value1 = value1;
Value2 = value2;
}
}
-
Joachim Van den Bogaert
Re: Method returning multiple values?
Also check your design. If you need to return too many values, you
might consider refactoring your code and use an object instead,
Regards,
Joachim
Comment
Comment