Tuples in C#



A tuple in C# is a lightweight data structure that allow us to group the multiple items of the different type into a single unit. It is a convenient way to handle a fixed number of the related values without the need to define the custom class or structure.

It was introduced in .NET Framework 4.0. A tuple can hold between 1 and 8 elements, meaning you can store up to 8 values in one tuple. If you try to add more than 8 elements, the compiler will give an error.

Let's understand the C# tuple with the following example

using System;

public class myClass {
   static public void Main() {
      // Creating a Tuple
      var tuple = ("Hello", "Tutorialspoint", 123, true);
      
      // Accessing the Elements
      Console.WriteLine(tuple.Item1);
      Console.WriteLine(tuple.Item2);
      Console.WriteLine(tuple.Item3);
      Console.WriteLine(tuple.Item4);
   }
}

As shown in the above code, we created a Tuple and accessed its elements using the "tuple.Item" property. So, we can access tuple elements in C# by using their default property names: Item1, Item2, Item3, etc., based on their position.

Declaration of Tuple in C#

Declaring a tuple with three elements: an int, a string, and a bool

Tuple<int, string, bool> myTuple = new Tuple<int, string, bool<(1, "Hello", true);

Accessing elements using Item1, Item2, etc.

Console.WriteLine(myTuple.Item1);
Console.WriteLine(myTuple.Item2);

Features of C# Tuple

Here are some of the important features of a C# tuple -

  • We can store multiple data into a single data set.
  • We can create, manipulate, and access data sets.
  • We can represent multiple data into a single data set.
  • Allows us to return multiple values without using out parameter.
  • We can also store duplicate elements as well.
  • It also allows us to pass multiple values to a method with the help of single parameters.

Example: How to Use Tuple

In this example, we create a tuple containing value a string, an integer, and a double.

using System;
class myClass {
   static void Main() {
      // Creating a Tuple with three elements
      Tuple<string, int, double> student = new Tuple<string, int, double>("Aman", 25, 85);

      // Accessing Tuple elements using Item1, Item2, Item3
      Console.WriteLine("Student Name: " + student.Item1);
      Console.WriteLine("Age: " + student.Item2);
      Console.WriteLine("Percentage: " + student.Item3);
   }
}

Following is the output

Student Name: Aman
Age: 25
Percentage: 85

Creating a Tuple in C#

There are two way to create a tuple in C# −

  • Using Constructor
  • Using Create Method

Creating a Tuple in C# using Constructor Method

We can create a tuple in C# using the Tuple<T> class constructor. A tuple can hold up to 8 elements, if you try to add more than 8, the compiler will show an error.

Tuple <T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8)

In the following example, we demonstrate how to create a Tuple in C# using its constructor −

using System;
public class myClass {
   public static void Main() {
      // Tuple with one element
      Tuple<string> t1 = new Tuple<string>("TutorialsPoint");

      // Tuple with three elements
      Tuple<string, string, int> t2 = new Tuple<string, string, int>("C#", ".NET", 13);

      // Accessing tuple elements
      Console.WriteLine(t1.Item1);
      Console.WriteLine(t2.Item1 + " - " + t2.Item2 + " - " + t2.Item3);
   }
}

When you run this code, it will produce the following output

TutorialsPoint
C# - .NET - 13

Creating a Tuple in C# using Create Method

The Tuple class provides a static Create() method that allows us to create tuple objects without specifying the type of each element explicitly.

We use the Create() method because, when using the tuple constructor, we need to specify the type of each element stored in the tuple, which makes the code lengthy.
// Method for 1-tuple
Create(T1)
.
.
.
// Method for 8-tuple
Create(T1, T2, T3, T4, T5, T6, T7, T8)

In the following example, we demonstrate how to create a Tuple in C# using its create method −

using System;
public class myClass {
   static public void Main() {
      // Creating 1-tuple
      var t1 = Tuple.Create("TutorialsPoint");

      // Creating 4-tuple
      var t2 = Tuple.Create("C#", ".NET", 13);

      // Creating 8-tuple
      var t3 = Tuple.Create(1,2,3,4,5,6,7,8);
	  Console.WriteLine(t1.Item1);
	  Console.WriteLine(t2.Item1);
	  Console.WriteLine(t3.Item4);
   }
}

Following is the output:

TutorialsPoint
C#
4

Nested Tuples in C#

A nested tuple is a tuple that is inserted as an element within another tuple. When we want to add more than eight elements in the same tuple, we need to use a nested tuple. A nested tuple is accessed using the "Rest" property.

Let's see how to create a nested tuple −

Tuple<string, int, Tuple<string, int>> nestedTuple =
   new Tuple<string, int, Tuple<string, int>>(
      "OuterValue", 100,
      new Tuple<string, int>("InnerValue", 200)
   );

Example: Accessing the Elements of a Nested Tuple:

In this example, we create a nested tuple, and then we access the elements using the "Rest" property −

using System;
public class MyClass {
   public static void Main() {
      // Nested Tuple
      var myTuple = Tuple.Create(1, 2, "TutorialsPoint", Tuple.Create(10, 20, 30, 40));

      Console.WriteLine("Element of outer tuple (Item3): " + myTuple.Item3);
      Console.WriteLine("Element of outer tuple (Item2): " + myTuple.Item2);

      // Accessing nested tuple
      Console.WriteLine("Nested tuple: " + myTuple.Item4);
      Console.WriteLine("First element of nested tuple: " + myTuple.Item4.Item1);
   }
}

Following is the output

Element of outer tuple (Item3): TutorialsPoint
Element of outer tuple (Item2): 2
Nested tuple: (10, 20, 30, 40)
First element of nested tuple: 10

Tuple as a Method Parameter in C#

A Tuple as a method parameter in C# allowing us to passing a tuple to a method instead of passing multiple separate arguments.

It allows you to send a group of related values together as a single parameter, making out code cleaner and more organized.

Example: Tuple as a Method Parameter

In the following example, we create a tuple and pass it in a function as a parameter in C#

using System;
class myClass {
   // Function with Tuple as a parameter
   static void DisplayStudentDetails(Tuple<string, int, int> student) {
      Console.WriteLine("Name: " + student.Item1);
      Console.WriteLine("Age: " + student.Item2);
      Console.WriteLine("Percentage: " + student.Item3);
   }

   static void Main() {
      var studentTuple = Tuple.Create("Aman", 25, 88);

      // Passing tuple as a parameter
      DisplayStudentDetails(studentTuple);
   }
}

Following is the output -

Name: Aman
Age: 25
Percentage: 88

Tuple as a Return Type in C#

Tuples in C# allow a method to return multiple values without having to define a custom class or structure.

Why Use a Tuple as a Return Type?

We use a tuple as a return type because a method can only return one value. However, sometimes we might want to return two or more related values; in such cases, we use a tuple as a return type.

Example: Return Sum, and Avg

In the following example, we create a tuple that returns the sum and average −

using System;

class myProgram {
   // Method returning a tuple (int, double)
   static (int sum, double average) Calculate(int a, int b, int c) {
      int total = a + b + c;
      double avg = total / 3.0;
      
      // returning tuple
      return (total, avg);
   }
   static void Main() {
      // Receive tuple result
      var result = Calculate(10, 20, 30);
      
      // Access tuple elements
      Console.WriteLine("Sum: " + result.sum);
      Console.WriteLine("Average: " + result.average);
   }
}

Following is the output

Sum: 60
Average: 20

Conclusion

A Tuple in C# is a lightweight data structure that stores multiple related values together. It is a reference type, not a value type. A Tuple can hold up to 8 elements; however, you can nest another Tuple inside it to store more values if needed. Tuples can also be passed as method parameters and returned from methods.

Advertisements