Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 830
Jun HU Avatar asked Jan 25 '13 09:01

Jun HU


People also ask

Can I return multiple values in C?

New programmers are usually in the search of ways to return multiple values from a function. Unfortunately, C and C++ do not allow this directly.

How do I pass multiple values in return?

To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.

Can I make a function return multiple values?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values. There is no specific syntax for returning multiple values, but these methods act as a good substitute.

How does a function return multiple values using pointer in C?

Pointers in C We can use pointers in C to return more than one value from the function by passing pointers as function parameters and use them to set multiple values, which will then have visibility in the caller function.


1 Answers

Use Tuple class.

  public Tuple<int,int> f()
  {
        Tuple<int,int> myTuple = new Tuple<int,int>(5,5);
        return myTuple;
  }
like image 138
D J Avatar answered Nov 04 '22 05:11

D J