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.
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.
To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.
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.
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.
Use Tuple class.
public Tuple<int,int> f()
{
Tuple<int,int> myTuple = new Tuple<int,int>(5,5);
return myTuple;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With