0

If I have a method like this:

private void RunExecute()
{
    var rc1 = doStuff(2);
    var rc2 = doStuff(1);
}

Is there any way that I can return both rc1 and rc2 instead of the void without creating a special class and using that as the return type and without declaring rc1 and rc2 as out parameters?

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

5

You can use Tuples

private (T,T) RunExecute()
{
    var rc1 = doStuff(2);
    var rc2 = doStuff(1);
    return (rc1,rc2)
}

Where T is type returned by doStuff

For example, if doStuff return int,

private (int,int) RunExecute()

To call the method and use the results, you can make use of the syntax

var (p1,p2) = RunExecute();

An alternative approach using Tuples is naming the Tuple elements. For example, during declaration.

private (int returnValue1,int returnValue2) RunExecute()

and calling it.

var result  = RunExecute();
Console.WriteLine(result.returnValue1);
Console.WriteLine(result.returnValue2);

PS: If you are using C# <7.0, you would have to limit yourself to following syntax.

private Tuple<int, int> RunExecute()
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51