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?
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.
Multiple values cannot be returned from a function in C or C++.
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;
}
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;
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