TAGS :Viewed: 15 - Published at: a few seconds ago

[ How to achieve multiple return values in C# like python style ]

I have a python script:

def f():
    a = None
    b = None
    return (a, b)


a, b = f()

It's so easy to achieve multiple return values in python. And now I want to achieve the same result in C#. I tried several ways, like return int[] or KeyValuePair. But both ways looked not elegant. I wonder a exciting solution. thanks a lot.

Answer 1


Use Tuple class.

  public Tuple<int,int> f()
  {
        Tuple<int,int> myTuple = new Tuple<int,int>(5,5);
        return myTuple;
  }

Answer 2


Unfortunately, C# does not support this. The closest you can get is to use out parameters:

void f(out int a, out int b) {
    a = 42;
    b = 9;
}

int a, b;
f(out a, out b);

Answer 3


You can obviously do

object F(out object b)
{
    b = null;
    return null
}

object b;
var a = F(out b)

but better to use Tuple with a functional style,

Tuple<object, object> F()
{
    return Tuple.Create<object, object>(null, null);
}

var r = F();
var a = r.Item1;
var b = r.Item2;

but, since in c# you can be explicit, why not define your return type.

struct FResult
{
    public object A;
    public object B;
}

FResult F()
{
    return new FResult();
}

var r = F();
var a = F.A;
var b = F.B;

This seems like a small price to pay for the semantic benefits.