简体   繁体   中英

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.

Use Tuple class.

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

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);

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.

This feature is available in C#7 with .Net 4.7.

private (string a, string b) f()
{
    return (a: null, b: null);
    // or simply: return (null, null);
}

var (a, b) = f();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM