C# Tuple: How to work with a Tuple in C#?

A tuple in C# is a data structure that allows us to store elements of different data types. It was first introduced with .NET Framework 4.0 and allowed a maximum of 8 elements to be stored. Any attempt to store more than eight elements will result in a compiler error.

Syntax:

Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
C# Tuple
C# Tuple

What is the need for C# Tuple?

There were the following different ways to return multiple values from a C# method before the tuple was introduced in C#.

  • By using a class, struct, or record type
  • By using the out parameter and
  • By using the dynamic return type of a method

Tuples solve this problem by storing different data types in a single data set. For example, Tuple can be useful when you want to store the details of a User in just one entity, such as Name, ID, Address, and Phone Number. With Tuples, you don’t need to create any separate data structure to store data of different types.

A tuple can be used to return multiple values from a method or to pass multiple values to a method.

Features of Tuple Types

  • Tuple allows multiple data types to be stored in a single lightweight data structure.
  • Tuple types support the == and != operators.
  • It allows a method to return multiple values without the use of the out keyword.
  • You can store duplicate elements in tuple types.
  • It allows multiple values to be passed to a method with a single parameter.
  • Tuple properties are all readonly which means they cannot be changed once they are created.
  • The size of a tuple is fixed as it cannot be changed once defined when the tuple is created.

Example 1:

Let’s see an example of creating a Tuple to store User information.

// C# program to demonstrate the tuple types in C#
using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Creating Tuple of three values Name, Id, and Address 
            var user = new Tuple<string, int, string>("Shekh Ali", 101, "Delhi");
            Console.WriteLine("====== User's Information ======");
            Console.WriteLine($" Name :{user.Item1}");
            Console.WriteLine($" Id   : { user.Item2}");
            Console.WriteLine($" Address :  {user.Item3}");
            Console.ReadLine();
        }
    }
}

Output:

Tuple in CSharp example

Create Tuple in C#

Tuples can be created in various ways in C# such as:

  • Using Parentheses
  • Using the Tuple.Create() method
  • Class-based approach Tuple<T>

C# Tuple Using Parentheses

You can create a tuple by directly assigning different values ​​using Parentheses ().

Example 2:

using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Creating a tuple containing 3 elements Name, Id, and Address 
            (string,int,string) user = ("Shekh Ali", 101, "Delhi");
            Console.WriteLine(user);
            Console.ReadLine();
        }
        // Output: (Shekh Ali, 101, Delhi)
    }
}

C# Tuple Example Using Create() Method

We can use static methods of the Tuple class to create a Tuple without providing the type of each element. In the following code snippet, we are using  Tuple.Create() method to create a tuple.

using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            var User = Tuple.Create("Shekh Ali",28, "Delhi");
            
            var TupleMaxLimit = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
            Console.WriteLine($"The {nameof(User)} has the following elements: {User}");    
            Console.WriteLine($"The {nameof(TupleMaxLimit)} has the following elements: {TupleMaxLimit}");

            Console.ReadLine();
        }
    }
}

Output:

Tuple in CSharp using create method

Class based approach Tuple<T>

We can use the  Tuple<T>  class to create a tuple with the specific length and type of the elements we want to store.

using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {         
            // Creating tuple to store User's name and age.
            Tuple<string, int> User = new Tuple<string, int>("Shekh Ali", 29);         
            Console.WriteLine($"The {nameof(User)} contains the following elements: {User}");          
            Console.ReadLine();
           // Output:
           // The User contains the following elements: (Shekh Ali, 29)
        }
    }
}

How to access elements from a Tuple?

Tuple elements can be accessed using the  Item  property.
For example: Item1, Item2, Item3, etc., up to the Item7 property. The Item1 property returns the first element, the Item2 property returns the second element, and so on. The last element (8th element) is returned using the Tuple’s  Rest  property.

Example: Accessing elements from the Tuple.

            var numberList = Tuple.Create(1, 2, 3, 4, 5, 6, 7, "Eight");
            Console.WriteLine(numberList.Item1); // returns 1
            Console.WriteLine(numberList.Item2); // returns 2
            Console.WriteLine(numberList.Item3); // returns 3
            Console.WriteLine(numberList.Item4); // returns 4
            Console.WriteLine(numberList.Item5); // returns 5
            Console.WriteLine(numberList.Item6); // returns 6
            Console.WriteLine(numberList.Item7); // returns 7
            Console.WriteLine(numberList.Rest); // returns (Eight)
            Console.WriteLine(numberList.Rest.Item1); // returns Eight       
            Console.ReadLine();        

In general, the 8th position is designated for the nested tuple, which can be accessed via the Rest property.

Nested Tuple

You can create a tuple within another tuple. A tuple inside a tuple is called a nested tuple.
If you want your tuple to contain more than 8 elements, you can do this by nesting another tuple object as the 8th element. The last nested tuple can be accessed using the Tuple’s Rest property. To access the elements of the nested tuple, use the property. Rest.Item1.Item<ElementNumber> 

Example: Nested Tuple

The following code snippet illustrates how you can create a nested tuple.

// C# program to demonstrate the Nested tuple in C#
using System;
namespace NestedTupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {
           // Nested Tuple Example 1
            var nestedTuple = Tuple.Create(100, "Shekh Ali", new Tuple<int, string>(101, "Roman"));
            Console.WriteLine(nestedTuple.Item1); // 100
            Console.WriteLine(nestedTuple.Item2); // Shekh Ali
            Console.WriteLine(nestedTuple.Item3.Item1); // 101
            Console.WriteLine(nestedTuple.Item3.Item2); // Roman

            // Nested Tuple Example 2

            var numberList = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));
            Console.WriteLine(numberList.Item1); // returns 1
            Console.WriteLine(numberList.Item2); // returns 2
            Console.WriteLine(numberList.Item7); // returns 7
            Console.WriteLine(numberList.Rest.Item1); // returns (8,9,10)
            Console.WriteLine(numberList.Rest.Item1.Item1); // 8
            Console.WriteLine(numberList.Rest.Item1.Item2); // 9
            Console.WriteLine(numberList.Rest.Item1.Item3); // 10
            Console.ReadLine();          
        }
    }
}

The nested tuple object can be placed anywhere in the sequence. It is, however, recommended that the nested tuple be placed at the end of the sequence so that it can be accessed using the Tuple’s Rest property.

How to use a tuple in a method?

A tuple can be used when you need to pass a data set as a single parameter of a method without using the ref and out parameters.

Let’s create a C# program to demonstrate the tuple as a method parameter in C#.

using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {
           // Tuple as method parameter
            var tuple = Tuple.Create(100, "Shekh Ali");

            Program.DisplayUser(tuple);
            Console.ReadLine();          
        }
        static void DisplayUser(Tuple<int, string> user)
        {
            Console.WriteLine($"Id = { user.Item1}");
            Console.WriteLine($"Name = { user.Item2}");          
        }
        // Output:
        // Id = 100
        // Name = Shekh Ali
    }
}

Returning Multiple Values Using Tuples in C#

You can return multiple values as a single variable from a method using tuples.
The following code snippet is returning a tuple with three values Id, Name, and Country.

using System;
namespace TupleExample
{
    class Program
    {
        public static void Main(string[] args)
        {          
            var tuple = Program.GetUserDetail();

            Console.WriteLine($"Id = { tuple.Item1} , Name = { tuple.Item2} , Country = { tuple.Item3}  ");

            Console.ReadLine();          
        }
        static Tuple<int, string, string> GetUserDetail()
        {
            Tuple<int, string,string> user = new Tuple<int, string, string>(100, "Shekh Ali","INDIA");
            return user;               
        }
        // Output:  Id = 100 , Name = Shekh Ali , Country = INDIA
    }
}

FAQ

Q: Is it a good idea to use tuple in C#?

Yes, If you want to return multiple values from a method without a ref or out parameter then you can use tuples, A tuple allows you to combine multiple values of different data types into a single object without creating a custom class.

Q: Why is a tuple better than an array?

Arrays can only store values of similar data types, whereas tuples allow you to store data of different types in a single variable.

Q: Why do C# tuples consume less memory?

Tuples are stored in a single block of memory and are immutable, so no extra space is required to store new objects.

Q: What is the maximum size of a tuple in C#?

Tuples have a limit to hold a maximum of 8 elements. If you want to create a Tuple with more than eight elements, you have to create nested Tuples.

Q: Is it better to use a tuple or a dictionary?

A tuple can contain multiple values of different datatypes, whereas a dictionary can only contain one datatype value at a time. Tuples are useful when you need to return multiple values from a method.

References: MSDN-Tuple types, tutorialsteacher- C#-Tuple

Related articles:

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments