Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a function to return two values?

Tags:

c#

Is it possible for a function to return two values? Array is possible if the two values are both the same type, but how do you return two different type values?

like image 266
iTayb Avatar asked Mar 12 '10 16:03

iTayb


People also ask

Can I return 2 values from a function in Python?

You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list containing the number of miles to run each week. Data structures in Python are used to store collections of data, which can be returned from functions.

Is it possible to return two values by any function * No Yes?

Multiple values cannot be returned from a function in C or C++.


2 Answers

Can a function return 2 separate values? No, a function in C# can only return a single value.

It is possible though to use other concepts to return 2 values. The first that comes to mind is using a wrapping type such as a Tuple<T1,T2>.

Tuple<int,string> GetValues() {
  return Tuple.Create(42,"foo");
}

The Tuple<T1,T2> type is only available in 4.0 and higher. If you are using an earlier version of the framework you can either create your own type or use KeyValuePair<TKey,TValue>.

KeyValuePair<int,string> GetValues() {
  return new KeyValuePair<int,sting>(42,"foo");
}

Another method is to use an out parameter (I would highly recomend the tuple approach though).

int GetValues(out string param1) {
  param1 = "foo";
  return 42;
}
like image 194
JaredPar Avatar answered Oct 11 '22 01:10

JaredPar


In a word, no.

But you can define a struct (or class, for that matter) for this:

struct TwoParameters {
    public double Parameter1 { get; private set; }
    public double Parameter2 { get; private set; }

    public TwoParameters(double param1, double param2) {
        Parameter1 = param1;
        Parameter2 = param2;
    }
}

This of course is way too specific to a single problem. A more flexible approach would be to define a generic struct like Tuple<T1, T2> (as JaredPar suggested):

struct Tuple<T1, T2> {
    public T1 Property1 { get; private set; }
    public T2 Property2 { get; private set; }

    public Tuple(T1 prop1, T2 prop2) {
        Property1 = prop1;
        Property2 = prop2;
    }
}

(Note that something very much like the above is actually a part of .NET in 4.0 and higher, apparently.)

Then you might have some method that looks like this:

public Tuple<double, int> GetPriceAndVolume() {
    double price;
    int volume;

    // calculate price and volume

    return new Tuple<double, int>(price, volume);
}

And code like this:

var priceAndVolume = GetPriceAndVolume();
double price = priceAndVolume.Property1;
int volume = priceAndVolume.Property2;
like image 34
Dan Tao Avatar answered Oct 11 '22 02:10

Dan Tao