Return multiple values from methods

Return multiple values from methods

In this article, I am going to explain how tuples can be used in C# 7 onwards to return multiple values.

Consider the following code from the console application. The method GetDivisionResults accepts two parameters namely number and divisor and returns two integers that are quotient and remainder.

  • static void Main(string[] args)
  • {
  • int number = 17;
  • int devisor = 5;
  • var result = GetDivisionResults(17, 5);
  • Console.WriteLine(“Quotient is ” + result.Item1);
  • Console.WriteLine(“Remainder is ” + result.Item2);
  • }
  • static (int, int) GetDivisionResults(int number, int divisor)
  • {
  • int quotient = number / divisor;
  • int remainder = number % divisor;
  • return (quotient, remainder);
  • }

The following function definition defines a function that returns two integer values as tuples.

  • (int, int) GetDevisionREsults(int number, int devisor)

(int, int) – defines the return type of the method, which is a tuple contains two integers. I am not concerned about the logic of the application, but see how it returns two numbers.

  • return (quotient, remainder);

Cool! Right. Let us evaluate how we can access the return values.

  • Console.WriteLine(“Quotient is ” + result.Item1);
  • Console.WriteLine(“Remainder is ” + result.Item2);

As you can see the values returned are accessed by the relative position in the Tuple. But using .Item1, .Item2 etc. from Tuple variable is not friendly. Luckily C# 7 gives you an option to define the variable names in tuples. Consider the following example.

  • static void Main(string[] args)
  • {
  • int number = 17;
  • int devisor = 5;
  • (int quotient, int remainder) = GetDivisionResults(17, 5);
  • Console.WriteLine(“Quotient is ” + quotient);
  • Console.WriteLine(“Remainder is ” + remainder);
  • }
  • static (int, int) GetDivisionResults(int number, int divisor)
  • {
  • int quotient = number / divisor;
  • int remainder = number % divisor;
  • return (quotient, remainder);
  • }

About the author

admin administrator

Leave a Reply