How to create 2-tuple or pair tuple 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.

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 tuple = new Tuple(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
raja
Published on 07-Nov-2019 05:56:57
Advertisements