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 = MultipleViaArray();
int a = vals[0], b = vals[1];
// or...
a = MultipleViaOut(out b);
// or...
var tuple = MultipleViaTuple();
a = tuple.Value1;
b = tuple.Value2;
}
static int[] MultipleViaArray()
{
return new int[] { 5, 7 };
}
static int MultipleViaOut(out int otherValue)
{
otherValue = 5;
return 7;
}
static Tuple<int, intMultipleViaTuple()
{
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;
}
}