How to return multiple values in C# 7? [closed]
Solution 1:
What do you mean by natively?
C# 7 has a new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.
Take the following function for instance:
(string, string, string) MyCoolFunction() // tuple return type
{
//...
return (firstValue, secondValue, thirdValue);
}
Which can be used like this:
var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;
Or by using deconstruction syntax
(string first, string second, string third) = MyCoolFunction();
//...
var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables
Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).
Solution 2:
You are looking for Tuples. This is an example:
static (int count, double sum) Tally(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
return (count, sum);
}
...
var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");
Example stolen from http://www.thomaslevesque.com/2016/07/25/tuples-in-c-7/