What is a Tuple in C# and When to Use It


Tuple is a generic static class that was added to C# 4.0 and it can hold any amount of elements, and they can be any type we want. So using tuple, we can return multiple values.One great use of tuple might be returning multiple values from a method. It provides an alternative to "ref" or "out" if you have a method that needs to return multiple new objects as part of its response.

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.

We can create a Tuple using the Create method. This method provide to 8 overloads, so we can use a maximum of 8 data types with a Tuple.

Followings are overloads

Create(T1)- Tuple of size 1
Create(T1,T2)- Tuple of size 2
Create(T1,T2,T3) – Tuple of size 3
Create(T1,T2,T3,T4) – Tuple of size 4
Create(T1,T2,T3,T4,T5) – Tuple of size 5
Create(T1,T2,T3,T4,T5,T6) – Tuple of size 6
Create(T1,T2,T3,T4,T5,T6,T7) – Tuple of size 7
Create(T1,T2,T3,T4,T5,T6,T7,T8) – Tuple of size 8

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;   
  5. namespace EDUDOTNET_TupleDemo  
  6. {  
  7.     class EDUDOTNET  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             //This represents a tuple of size 3 (Create a new 3-tuple, or Triple) with all string type  
  12.             var tuple = Tuple.Create<stringstringstring>("EDUDOTNET""IT""SOLUTION");  
  13.             Console.WriteLine(tuple);   
  14.             //This represents a tuple of size 2 (Create a new 2-tuple, or Pair) with int & string type  
  15.             var tuple1 = Tuple.Create<intstring>(51, "CTO-EDUDOTNET");  
  16.             Console.WriteLine(tuple1);          
  18.             //We can also access values of Tuple using ItemN property. Where N point to a particular item in the tuple.  
  19.             //This represents a tuple of size 4 (Create a new 4-tuple, or quadruple) with 3 string & 1 int type  
  20.             var tuple2 = Tuple.Create<intstringstringstring>(1, "Khumesh""EDUDOTNET""IT-Solution");  
  21.             Console.WriteLine(tuple2.Item1);  
  22.             Console.WriteLine(tuple2.Item2);  
  23.             Console.WriteLine(tuple2.Item3);  
  24.             Console.WriteLine(tuple2.Item4);  
  25.             Console.WriteLine("Enjoying With Tuple.......... :)");  
  26.             Console.ReadLine();  
  27.         }  
  28.     }  
  29. }  
Next Recommended Reading Remove AM PM from Time String using C#