Method returning multiple values?

  • Thread starter Thread starter satyanarayan sahoo
  • Start date Start date
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, int> MultipleViaTuple()
{
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;
}
}
 
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top