Tuple in C#

C# 4.0 included a new feature called Tuple. A tuple is a data structure that has a specific number and sequence of elements.

Tuple can be used in several ways. Let’s see, how tuple can be used to return multiple values from a method.

In the example, we are passing two integer values to the method and method is performing four mathematical operations (add, subtract, multiplication, division) and returning a tuple with 3 integer and 1 double values for these operations.

  1. using System;  
  2. namespace ConsoleApplication1  
  3. {  
  4.     class clsMain  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             clsTuple objTuple = new clsTuple();  
  9.             var tuple = objTuple.Operations(10, 3);  
  10.             Console.WriteLine("Sum:{0}, Subtract:{1}, Multiply :{2}, Division:{3}", tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4);  
  11.             System.Threading.Thread.Sleep(2000);  
  12.         }  
  13.     }  
  14.     class clsTuple  
  15.     {  
  16.         public Tuple < intintintdouble > Operations(int i, int j)  
  17.         {  
  18.             return Tuple.Create(i + j, i - j, i * j, Convert.ToDouble(i) / j);  
  19.         }  
  20.     }  
  21. }  
Ebook Download
View all
Learn
View all