Tuple Class in C#


The Tuple<T1, T2> class represents a 2-tuple, which is called pair. A tuple is a data structure that has a sequence of elements.

It is used in −

  • Easier access to a data set.
  • Easier manipulation of a data set.
  • To represent a single set of data.
  • To return multiple values from a method
  • To pass multiple values to a method

It has two properties −

  • Item1 − Get the value of the current Tuple<T1, T2> object's first component.

  • Item2 − Get the value of the current Tuple<T1, T2> object's second component.

Example

Let us now see an example to implement the 2-tuple in C# −

using System;
public class Demo {
   public static void Main(string[] args) {
      Tuple<string,string> tuple = new Tuple<string,string>("jack", "steve");
      Console.WriteLine("Value = " + tuple.Item1);
      if (tuple.Item1 == "jack") {
         Console.WriteLine("Exists: Tuple Value = " +tuple.Item1);
      }
      if (tuple.Item2 == "david") {
         Console.WriteLine("Exists: Tuple Value = " +tuple.Item2);
      }
   }
}

Output

This will produce the following output −

Value = jack
Exists: Tuple Value = jack

Example

Let us now see another example to implement the 2-tuple in C# −

using System;
public class Demo {
   public static void Main(string[] args) {
      Tuple<int,string> tuple = new Tuple<int,string>(20, "steve");
      Console.WriteLine("Value = " + tuple.Item1);
      if (tuple.Item1 == 20) {
         Console.WriteLine("Exists: Tuple Value = " +tuple.Item1);
      }
      if (tuple.Item2 == "david") {
         Console.WriteLine("Exists: Tuple Value = " +tuple.Item2);
      }
   }
}

Output

This will produce the following output −

Value = 20
Exists: Tuple Value = 20

Updated on: 05-Nov-2019

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements