A tuple in C# is a special kind of data structure used for holding the different types of data types. In .NET concepts of tuple were introduced in the .Net framework 4 by Tupple<T> generic class.

One of the simplest examples is when you want to return more than one object but don’t want to have a type created with only two properties. We can utilize the tuple data type.

If you are not using the C# 7 version then the tuple can be included using the NuGet package System.ValueTuple

Tuple in C# using NuGet package
Tuple using Nuget Package

Tuple<> and Tuple both of the classes can be found inside the system namespace in C#.

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

How to create a tuple in C#

Tuple can be created using either direct instance creation or the static factory method.

Create a tuple using the instance member

In this example, we will be creating an instance of tupple, which holds the information about employee details. While creating a tupple using an instance member, we have to specify the data type for each time in the tupple.

var empInfo=new Tuple<string,string,int>("Deependra","Kushwaha",30);

Create a tuple in C# using the static method

Tuple can be created using the static methods provided in the Tuple class. In this case, we don’t need to specifically mention the data types for each item in the tuple.

var tupple = Tuple.Create("Deependra","Kushwaha","30");

How to access tupple in C#

Tuple can hold a maximum of eight items, for each item there is a dedicated property starting with item1,item2, and so on and the last item is called TRest which is the 8th item in the tupple class.

      var tuple = Tuple.Create("Deependra", "Kushwaha", 30, "India", "Karnataka", "Bangalore", "Whitefield", 560029);
            
            Console.WriteLine(tuple.Item1);
            Console.WriteLine(tuple.Item2);
            Console.WriteLine(tuple.Item3);
            Console.WriteLine(tuple.Item4);
            Console.WriteLine(tuple.Item5);
            Console.WriteLine(tuple.Item6);
            Console.WriteLine(tuple.Item7);
            Console.WriteLine(tuple.Rest);
            

In the above example first argument “Deependra” will be assigned to the item1 property in tupple, “kushwah” will be assigned to the item2 property and age will be assigned to the third property and the last item 560029 can be accessed by Rest property which is the last item in the tuple.

When to use tuple in C#

It can be used in multiple places like returning more than one element in the method. Taking tuple as a parameter.

Tuple as the return type in a method

In this example, we will create a DateTime helper method that returns back the two items in the tuple. Date as the first item and time as the second item.

Just to hold only these two properties, I don’t want to maintain a different class but rather use the tuple class.

static void Main(string[] args)
        {
            var dateAndTime = ExtractDateAndTime(DateTime.Now);
            Console.WriteLine($"Date: {dateAndTime.Item1}");
            Console.WriteLine($"Time: {dateAndTime.Item2}");
            Console.ReadKey();
        }


        private static Tuple<string, string> ExtractDateAndTime(DateTime dateTime)
        {
            var dateAndTime =
                new Tuple<string, string>(dateTime.Date.ToShortDateString(), dateTime.ToShortTimeString());
            return dateAndTime;
        }
Console output of tuple method exacting the date and time
Console output of tuple method exacting the date and time

We can also update the above method to return the list of tuples by just changing the return type of method.

   private static IEnumerable<Tuple<string, string>> ExtractDateAndTime(DateTime dateTime)
        {
            var dateAndTime =
                new Tuple<string, string>(dateTime.Date.ToShortDateString(), dateTime.ToShortTimeString());
            return new List<Tuple<string, string>>() { dateAndTime };
        }

Tuple as a method parameter

A tuple can be used as a method parameter for passing the multiple arguments. In this example, we are creating a method that takes the Tuple parameter with three items, the first and second as strings and the third as an integer.

using System;

namespace Demo.App
{
    class Program
    {
        static void Main(string[] args)
        {

            var tuple = Tuple.Create("Deependra", "Bangalore", 876);
            var employeeId = GenerateEmployeeId(tuple);
            Console.WriteLine($"Generated Employee ID : {employeeId}");
            Console.ReadKey();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="employeeDetail">Tuple("EmpName","Location",EmpId)</param>
        /// <returns></returns>
        private static string GenerateEmployeeId(Tuple<string, string, int> employeeDetail)
        {
            return
                $"{employeeDetail.Item1.Substring(0, 3)}{employeeDetail.Item2.Substring(0, 2)}{employeeDetail.Item3}".ToUpper();
        }

    }
}

Issue while using the tuple as a parameter in the method. The caller of the method will not beware of what the pass in those arguments until you specify in the form of comments on methods.

Adavantages of using tuple in code

  1. Multiple data types in a single data set
  2. Creation/manipulation and access to the data set
  3. Return of multiple values from methods without out
  4. Storing duplicate elements
  5. Passing multiple values to a method with a single parameter

Issues while using tuple in code

  • Code readability is the big issue while using a tuple.
  • A tuple is limited to using only 8 properties.

What is ValueTuple in C#?

The concept of ValueTuple was introduced in the C# version 7. An enhanced version of tuple data structure in the C#.

Valuetuple was introduced from .Net framework version 4.7 onwards. In case you are using the legacy framework, you can utilize the NuGet package available to support the value tuple in C#.

System.Value.Tuple

Create a value tuple in C#

As I mention earlier value tuple is the enhanced version of the tuple data structure. It can be created by just using the brackets around it. Also, it is not limited to any number of parameters you can pass into.

var empDetails = ("Deependra", "Kushwah", 30,"A");

How to access value tuple values in C#

As we can see empDetails tuple has four properties that can be accessed using the item plus the order number of the property.

var empDetails = ("Deependra", "Kushwah", 30,"A");
            
            Console.WriteLine(empDetails.Item1);
            Console.WriteLine(empDetails.Item2);
            Console.WriteLine(empDetails.Item3);
            Console.WriteLine(empDetails.Item4);

Named Member in ValueTuple

One of the bigger issues of using tuples is the naming of the parameters, which reduces the code readability.

By, using the named members in the ValueTuple we can overcome that issues as well.

            var empDetails = (FirstName:"Deependra", LastName: "Kushwah",Age: 30);
            
            Console.WriteLine(empDetails.FirstName);
            Console.WriteLine(empDetails.LastName);
            Console.WriteLine(empDetails.Age);

After seeing the above lines of code, your code reviewer will no longer complain about the readability of the code.

Other operations in ValueTuple remain the same as Tuple in C#.

Conclusion

In this article, we tried understanding the concepts of Tuple and ValueTuple in C# language. We also discussed the use cases of tuple data structure along with its pros and cons.

Also, We talked about the enhanced version of a tuple in C# 7. Which are a cleaner and easy-to-use version of tuple.

82 / 100