How can we return multiple values from a function in C#?

CsharpServer Side ProgrammingProgramming

In c# multiple values can be returned using the below approaches −

  • Reference parameters

  • Output parameters

  • Returning an Array

  • Returning a Tuple

Reference parameters

Example

class Program{
   static int ReturnMultipleValuesUsingRef(int firstNumber, ref int secondNumber){
      secondNumber = 20;
      return firstNumber;
   }
   static void Main(){
      int a = 10;
      int refValue = 0;
      var res = ReturnMultipleValuesUsingRef(a, ref refValue);
      System.Console.WriteLine($" Ref Value {refValue}");
      System.Console.WriteLine($" Function Return Value {res}");
      Console.ReadLine();
   }
}

Output

Ref Value 20
Function Return Value 10

Output parameters

Example

class Program{
   static int ReturnMultipleValuesUsingOut(int firstNumber, out int secondNumber){
      secondNumber = 20;
      return firstNumber;
   }
   static void Main(){
      int a = 10;
      int outValue = 0;
      var res = ReturnMultipleValuesUsingOut(a, out outValue);
      System.Console.WriteLine($" Out Value {outValue}");
      System.Console.WriteLine($" function Return Value {res}");
      Console.ReadLine();
   }
}

Output

Out Value 20
Function Return Value 10

Returning Arrays

Example

class Program{
   static int[] ReturnArrays(){
      int[] arrays = new int[2] { 1, 2 };
      return arrays;
   }
   static void Main(){
      var res = ReturnArrays();
      System.Console.WriteLine($"{res[0]} {res[1]}");
      Console.ReadLine();
   }
}

Output

1 2

Returning Tuple

Example

class Program{
   static Tuple<int, int>ReturnMulitipleVauesUsingTuples(){
      return new Tuple<int, int>(10, 20);
   }
   static void Main(){
      var res = ReturnMulitipleVauesUsingTuples();
      System.Console.WriteLine($"{res.Item1} {res.Item2}");
      Console.ReadLine();
   }
}

Output

10 20
raja
Published on 04-Aug-2020 10:23:05
Advertisements