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?
In C# you can return more than one value using an out parameter. See example in the TryParse method of Int32 struct. It returns bool and an integer in an out parameter.
You have basically (at least) two options, either you make an out parameter in addition to the return value of the function, something like T1 Function(out T2 second)
or you make your own class putting these two types together, something like a Pair<T1,T2>
. I personally prefer the second way but it's your choice.
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;
}
All of the possible solutions miss one major point; why do you want to return two values from a method? The way I see it, there are two possible cases; a) you are returning two values that really should be encapsulated in one object (e.g. height and width of something, so you should return an object that represents that something) or b) this is a code smell and you really need to think about why the method is returning two values (e.g. the method is really doing two things).
no but you can use an out parameter
int whatitis;
string stuff = DoStuff(5, out whatitis);
public string DoStuff(int inParam, out int outParam)
{
outParam = inParam + 10;
return "donestuff";
}
with C# 7, you can now return a ValueTuple
:
static (bool success, string value) GetValue(string key)
{
if (!_dic.TryGetValue(key, out string v)) return (false, null);
return (true, v); // this is a ValueType literal
}
static void Main(string[] args)
{
var (s, v) = GetValue("foo"); // (s, v) desconstructs the returned tuple
if (s) Console.WriteLine($"foo: {v}");
}
ValueTuple
is a value-type, which makes it a great choice for a return value compared with a reference-type Tuple
- no object needs to be garbage-collected.
Also, note that you can give a name to the values returned. It is really nice.
For that reason alone I wish it was possible to declare a ValueTuple
with only one element. Alas, it is not allowed:
static (string error) Foo()
{
// ... does not work: ValueTuple must contain at least two elements
}