When to use tuples in C#?

CsharpServer Side ProgrammingProgramming

Tuples are used when you want to return multiple values from a method without using ref or out parameters.

Tuples are used to pass multiple values to a method through a single parameter. Tuples can also be nested together

Example

Passig Tuples as a Parameter

class Program{
   static void DisplayTupleValues(Tuple<int, string, string> dummy){
      Console.WriteLine($"Id = { dummy.Item1}");
      Console.WriteLine($"Value1 = { dummy.Item2}");
      Console.WriteLine($"Value2 = { dummy.Item3}");
   }
   static void Main(){
      var dummy = Tuple.Create(1, "Dummy", "Tuple");
      DisplayTupleValues(dummy);
      Console.ReadLine();
   }
}

Output

Id = 1
Value1 = Dummy
Value2 = Tuple

Example

Tuple as a return type

class Program{
   static Tuple<int, string, string> ReturnTuple(){
      return Tuple.Create(1, "Value1", "Value2");
   }
   static void Main(){
      var returnValues = ReturnTuple();
      System.Console.WriteLine($"{returnValues.Item1} {returnValues.Item2}
      {returnValues.Item3}");
      Console.ReadLine();
   }
}

Output

1 Value1 Value2
raja
Published on 04-Aug-2020 06:56:08
Advertisements