Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

48
Views
How to return multiple values in C# 7?

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

11 months ago · Santiago Trujillo
3 answers
Answer question

0

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!).

11 months ago · Santiago Trujillo Report

0

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/

11 months ago · Santiago Trujillo Report

0

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);
    }
}
11 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.