Tuple

Tuple means a structure with multiple parts. This is introduced in the .Net Framework 4.0.
This allows for the creating of different types of variables or objects in a single data structure.
Features:

- We can have limited multiple data from 1 to 8 elements in a tuple and cannot be more than 8.

- We can read, modify, and add the data to the tuple.

- We can pass it as a parameter and return it as well from a method so it helps in the passing of returning multiple different types of data variables at a time.

We can create a Tuple in 2 ways:

1. By using Constructor:
    Passing as parameter.

Syntax:

Tuple (T1, T2) //2 tuple
Tuple(T1, T2, T3) //3 tuple

2. By using the Create method
   Using the inbuilt Create method and passing parameters.

Syntax:

Create(T1) // 1 tuple
Create(T1, T2) // 2 tuple

We can read elements from a tuple by using items. We need to use item1, item2 …. Item8 for
elements to read from element 1 to element8.

Example

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      var tuple1 = new Tuple <
      int,
      string,
      bool >
      (100, " TestTuple ", true);
      var tuple2 = Tuple.Create( " TestTuple2 ");
      var tupleResult1 = EligibleToVote(20);
      Console.WriteLine($ " Salary
      for Age 20 is: {
        tupleResult1.Item1
      }
      and
      Eligible to Vote is: {
        tupleResult1.Item2
      } ");
      var tupleResult2 = EligibleToVote(17);
      Console.WriteLine($ " Salary
      for Age 17 is: {
        tupleResult2.Item1
      }
      and
      Eligible to Vote is: {
        tupleResult2.Item2
      } ");
    }
    public static Tuple <
    int,
    bool >
    EligibleToVote(int age) {
      Tuple <
      int,
      bool >
      tuple = new Tuple <
      int,
      bool >
      (1000, false);
      if (age > 18) {
        tuple = new Tuple <
        int,
        bool >
        (20000, tuple.Item2);
      }
      else {
        tuple = new Tuple <
        int,
        bool >
        (tuple.Item1, true);
      }
      return tuple;
    }
  }
}

 

The output will be:

Salary for Age 20 is: 20000 and Eligible to Vote is: False
Salary for Age 17 is: 1000 and Eligible to Vote is: True

 

 

Related Tutorials