5

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.

5
  • 1
    The Tuple class is a little more elegant, msdn.microsoft.com/en-us/library/system.tuple.aspx Commented Jan 25, 2013 at 9:07
  • Are multiple return values a good and desirable thing? Should functions be able to return anonymous types? Commented Jan 25, 2013 at 9:21
  • You might try F#, which supports this: let f() = (14, 29) then let (a, b) = f() Commented Jan 25, 2013 at 9:24
  • 1
    @Jodrell they are very useful indeed. F#, for example, handles TryParse much more concisely than C#, because it returns out parameters as part of a tuple: let (success, result) = Int32.TryParse(someString) Commented Jan 25, 2013 at 9:25
  • @phoog, on consideration, I'm inclined to agree, as long as the types in the tuple are defined, unlike the OPs example. Commented Jan 25, 2013 at 9:30

4 Answers 4

6

Use Tuple class.

  public Tuple<int,int> f()
  {
        Tuple<int,int> myTuple = new Tuple<int,int>(5,5);
        return myTuple;
  }
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

does it like the reference parameter passing?
@JunHU: I don't understand - what is "it"?
2

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.

1 Comment

F# is type safe, but you can also have let f x = (x*2, x*x) and let (a, b) = f 5, which assigns the values 10 and 25 to a and b, respectively.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.