How to return multiple values in C# 7?

C#.NetC# 7.0

C# Problem Overview


Is it is possible to return multiple values from a method natively?

C# Solutions


Solution 1 - C#

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 - C#

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/

Solution 3 - C#

You can also implement like this:

public class Program
{
    public static void Main(string[] args)
    {
        
        var values=GetNumbers(6,2);
        Console.Write(values);
      
        
    }
    
    static KeyValuePair<int,int> GetNumbers(int x,int y)
    {
        return new KeyValuePair<int,int>(x,y);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCoder NewbieView Question on Stackoverflow
Solution 1 - C#SidView Answer on Stackoverflow
Solution 2 - C#user2657943View Answer on Stackoverflow
Solution 3 - C#MaganjoView Answer on Stackoverflow