What are Tuples in C#4.0?

CsharpProgrammingServer Side Programming

Tuples has a sequence of elements of different data types. It was introduced to return an instance of the Tuple<T> with no need to specify the type of each element separately.

Let us create a tuple with two elements. The following is how you declare a tuple. −

Tuple<int, string>person = new Tuple <int, string>(32, "Steve");

Now, for the example check for the first item in the tuple, which is an integer −

if (tuple.Item1 == 99) {
   Console.WriteLine(tuple.Item1);
}

Now check for second item in the tuple, which is a string −

if (tuple.Item2 == "Steve") {
   Console.WriteLine(tuple.Item2);
}

The following is an example to create a tuple with string and int items −

Example

 Live Demo

using System;
using System.Threading;

namespace Demo {
   class Program {

      static void Main(string[] args) {

         Tuple<int, string> tuple = new Tuple<int, string>(50, "Tom");

         if (tuple.Item1 == 50) {
            Console.WriteLine(tuple.Item1);
         }

         if (tuple.Item2 == "Jack") {
            Console.WriteLine(tuple.Item2);
         }
      }
   }
}

Output

50
raja
Published on 09-Aug-2018 10:24:16
Advertisements