C# Tuple

In c#, Tuple is a data structure and it is useful to store the sequence of elements of different data types. By using tuple we can return more than one value from the methods as a single set of data.

 

Tuples were introduced in .NET Framework 4.0 and the syntax of tuples will be like as shown below.

 

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

In .NET Framework, the Tuple will directly support only 1 to 7 elements. In case, if we want to create a tuple object to hold 8 or more elements, then we need to nest the tuple objects in the TRest property.

C# Create Tuple

Following is the example of creating a tuple object (user) with 4 elements.

 

Tuple<int, string, string, double> user = new Tuple<int, string, string, double>(1, "Suresh", "Hyderabad", 78.5);

 

Or

 

var user = new Tuple<int, string, string, double>(1, "Rohini", "Guntur", 90.5);

If you observe the above declarations, we created an instance of the Tuple class by specifying the type for each element to hold the details of the user in a single object.

 

As discussed, the tuple object which we create with Tuple class instance will directly support only 1 to 7 elements. If we define 8 or more elements, we will get a compile-time error like “The last element of an eight element Tuple must be a Tuple”.

 

Following is the invalid way of defining the tuple objects in c#.

 

// Invalid way

var numbers = new Tuple<int, int, int, int, int, int, int, int>(1, 2, 3, 4, 5, 6, 7, 8);

If you observe the above tuple object declarations, every time we are passing the values to the tuple object by specifying the type for each element and it’s like cumbersome. So, to avoid sending the type for each element, we need to create a tuple object by using the Tuple class helper method “Create”.

 

Following is the example of creating a tuple object by using the Tuple class static methodCreate” without specifying the types for each element.

 

var user = Tuple.Create(1, "Rohini", "Guntur", 90.5);

 

Or

 

var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);

If you observe the above code, we created a tuple object (numbers) by using the Create method with 8 elements. The Create method will directly support the creation of a tuple object from 1 to 8 elements.

 

So, if we create a tuple object with an instance of the Tuple class, then it will support only 1 to 7 elements. In case, if we create with Create method of Tuple class, then it will support 1 to 8 elements.

C# Access Tuple Elements

In c#, we can access the tuple object elements with Item<positionNumber> properties. For example, the first element can be accessed like Item1, the second element can be accessed like Item2, and so on based on our requirements.

 

Following is the example of accessing the tuple object elements in c#.

 

var user = Tuple.Create(1, "Rohini", "Guntur", 90.5);

var Id = user.Item1; // 1

var name = user.Item2; // Rohini

var location = user.Item3; // Guntur

 

var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);

var e1 = numbers.Item3; // 3

var e2 = numbers.Item4; // 4

var e3 = numbers.Rest; // (8)

var e4 = numbers.Rest.Item1; // 8

If you observe the above code snippet, we are accessing the 8th position of element using Rest property because the 8th position is for nested tuples and that can be accessed by using Rest property.

Uses of Tuple in C# 

In c#, tuples are commonly useful in the following scenarios.

 

  • To represent or return different data type elements as a single set of data.
  • To return multiple values from methods without using ref or out parameters.
  • To pass multiple values to a method with a single parameter.
  • Temporarily hold multiple values without creating a class or struct.

C# Tuple Example

Following is the example of creating and accessing the tuple object values in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            var user = Tuple.Create(1, "Rohini", "Guntur", 90.5);

            Console.WriteLine("*****User Details*****");

            Console.WriteLine("Id:{0}", user.Item1);

            Console.WriteLine("Name:{0}", user.Item2);

            Console.WriteLine("Location:{0}", user.Item3);

            Console.WriteLine("Percentage:{0}", user.Item4);

 

            var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);

            Console.WriteLine("*****Numbers*****");

            Console.WriteLine("{0}", numbers.Item1);

            Console.WriteLine("{0}", numbers.Item4);

            Console.WriteLine("{0}", numbers.Rest);

            Console.WriteLine("{0}", numbers.Rest.Item1);

            Console.ReadLine();

        }

    }

}

When we execute the above program, we will get the result like as shown below.

 

*****User Details*****

Id:1

Name:Rohini

Location:Guntur

Percentage:90.5

 

*****Numbers*****

1

4

(8)

8

C# Nested Tuples

As discussed, the Tuple will support only 8 elements. In case, if we want to include more than 8 elements in a tuple, then we need to nest another tuple object at 8th position and it can be accessed by using Rest property.

 

Following is the example of creating and accessing the nested tuples in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12));

            Console.WriteLine("*****Numbers*****");

            Console.WriteLine("{0}", numbers.Item1);

            Console.WriteLine("{0}", numbers.Item4);

            Console.WriteLine("{0}", numbers.Rest.Item1);

            Console.WriteLine("{0}", numbers.Rest.Item1.Item1);

            Console.WriteLine("{0}", numbers.Rest.Item1.Item4);

            Console.ReadLine();

        }

    }

}

If you observe the above example, we included more than 8 elements in a tuple object (numbers) by nesting another tuple object at 8th element and we are accessing nested tuple elements by using Rest property.

 

When we execute the above program, we will get the result like as shown below.

 

*****Numbers*****

1

4

(8, 9, 10, 11, 12)

8

11

In c#, the nested tuple object can be included anywhere in the sequence but it is recommended to place the nested tuple at the end of sequence so that it can be accessed by using Rest property.

 

Following is the example of including the nested tuple object at the 4th position of sequence in the defined tuple object.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            var numbers = Tuple.Create(1, 2, 3, Tuple.Create(8, 9, 10, 11, 12), 4, 5, 6, 7);           

            Console.WriteLine("*****Numbers*****");

            Console.WriteLine("{0}", numbers.Item1);

            Console.WriteLine("{0}", numbers.Item4);

            Console.WriteLine("{0}", numbers.Item4.Item1);

            Console.WriteLine("{0}", numbers.Item4.Item4);

            Console.WriteLine("{0}", numbers.Rest.Item1);

            Console.ReadLine();

        }

    }

}

If you observe the above example, we included nested tuple object at 4th position of sequence and accessing nested tuple object values using Item4 element.

 

When we execute the above program, we will get the result like as shown below.

 

*****Numbers*****

1

(8, 9, 10, 11, 12)

8

11

7

This is how we can include more than 8 elements in tuple object by nesting another tuple object at 8th element based on our requirements.

C# Tuple as Method Parameter

In c#, if we accept Tuple as a method parameter, then we can send multiple values to the method with a single parameter.

 

Following is the example of using a tuple as a method parameter in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            var user = Tuple.Create(1, "Rohini", "Guntur", 90.5);

            GetUserDetails(user);

            Console.ReadLine();

        }

        public static void GetUserDetails(Tuple<int, string, string, double> user)

        {

            Console.WriteLine("*****User Details*****");

            Console.WriteLine("Id:{0}", user.Item1);

            Console.WriteLine("Name:{0}", user.Item2);

            Console.WriteLine("Location:{0}", user.Item3);

            Console.WriteLine("Percentage:{0}", user.Item4);

        }

    }

}

If you observe the above example, we are sending tuple object (user) as a parameter to the GetUserDetails() method.

 

When we execute the above program, we will get the result like as shown below.

 

*****User Details*****

Id:1

Name:Rohini

Location:Guntur

Percentage:90.5

By using a tuple, we can send multiple values as a single parameter to the method based on our requirements.

C# Tuple as Return Type

In c#, we can use a tuple as a method return type to return the multiple values without using ref or out parameters.

 

Following is the example of using a tuple as the return type of method to return multiple values in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            var user = GetUserDetails();

            Console.WriteLine("*****User Details*****");

            Console.WriteLine("Id:{0}", user.Item1);

            Console.WriteLine("Name:{0}", user.Item2);

            Console.WriteLine("Location:{0}", user.Item3);

            Console.WriteLine("Percentage:{0}", user.Item4);

            Console.ReadLine();

        }

        public static Tuple<int, string, string, double> GetUserDetails()

        {

            var user = Tuple.Create(1, "Rohini", "Guntur", 90.5);

            return user;

        }

    }

}

If you observe the above example, we created a method GetUserDetails() with return type like a tuple object to return multiple values.

 

When we execute the above program, we will get the result like as shown below.

 

*****User Details*****

Id:1

Name:Rohini

Location:Guntur

Percentage:90.5

C# Tuple Limitations

Following are the limitations of tuple object in c#.

 

  • As discussed, the Tuple will directly support only 8 elements. If we want to store more than 8 elements, then we need to use nested tuples.
  • The tuple object properties can be accessed by using the name pattern like ItemX and it won’t make sense to access the properties like Item1, Item2, etc.
  • The Tuple classes will cause more performance issue because they are reference types.

To overcome the limitations of Tuple, the ValueTuple has been introduced in C# 7.0. In the next chapters, we will learn about ValueTuple in detail with examples.

 

PREVIOUS

C# Task
 

NEXT

C# ValueTuple  
 

Topics Covered