How to achieve multiple return values ​​in C # such as python style

I have a python script:

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


a, b = f()

So easy to get multiple return values ​​in python. And now I want to achieve the same result in C #. I tried several ways, for example return int [] or KeyValuePair. But both methods did not look elegant. I wonder what a fascinating decision. Many thanks.

+5
source share
4 answers

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

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

int a, b;
f(out a, out b);
+3
source

Use the Tuple class.

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

, ,

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

object b;
var a = F(out b)

Tuple ,

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

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

# , .

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

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

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

.

+1

# 7 .Net 4.7.

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

var (a, b) = f();
0

All Articles