Splitting Tuples in C#

Splitting Tuples in C# with Examples

In this article, I am going to discuss Splitting Tuples in C# with examples. Please read our previous article before proceeding to this article where we discussed Tuples in C# with some examples. The Splitting Tuples in C# is a process of splitting a variable value into multiple parts and storing each part into a new variable. This is very useful when you are working with tuples in C# as we know Tuples are going to store multiple values. 

Why do we need to Split a Tuples in C#?

As we already discussed Tuples provides a light-weight way to retrieve multiple values from a method call. Once you retrieve the tuple, then you need to handle its individual elements. Handling this element one by one is really a dirty approach. We can overcome this by splitting the tuples in C#.

Let’s understand Splitting Tuples in C# with an example.
class Program
{
    static void Main()
    {
        var EmployeeDetails = GetEmployeeDetails(1001);

        var Name = EmployeeDetails.Item1;
        var Salary = EmployeeDetails.Item2;
        var Gender = EmployeeDetails.Item3;
        var Dept = EmployeeDetails.Item4;

        // Do something with the data.
        //here we are just printing the data in the console

        Console.WriteLine("Employee Details :");
        Console.WriteLine($"Name: {Name},  Gender: {Gender}, Department: {Dept}, Salary:{Salary}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (string, double, string, string) GetEmployeeDetails(long EmployeeID)
    {
        //based on the EmployyeID get the data from a database
        //here we are hardcoded the value
        string EmployeeName = "Pranaya";
        double Salary = 2000;
        string Gender = "Male";
        string Department = "IT";

        return (EmployeeName, Salary, Gender, Department);

    }
}

When you run the application, you will get the data as expected as shown below.

Splitting Tuples in C#

As shown in the above example the GetEmployeeDetails() method returns a tuple with 4 values and then we assigned each of its elements to a variable in a separate operation.

But from C# 7.0, now we can retrieve multiple elements from a tuple or retrieve multiple fields or properties values from an object in a single operation which is called Splitting Tuples in C#.

Different ways to deconstruct a tuple or Splitting Tuples in C#:

Way1: We can explicitly declare the type of each field inside the parentheses. Let’s modify the program as shown below to understand this concept.

class Program
{
    static void Main()
    {
        (string Name, double Salary, string Gender, string Dept) = GetEmployeeDetails(1001);

        // Do something with the data.
        //here we are just printing the data in the console

        Console.WriteLine("Employee Details :");
        Console.WriteLine($"Name: {Name},  Gender: {Gender}, Department: {Dept}, Salary:{Salary}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (string, double, string, string) GetEmployeeDetails(long EmployeeID)
    {
        //based on the EmployyeID get the data from a database
        //here we are hardcoded the value
        string EmployeeName = "Pranaya";
        double Salary = 2000;
        string Gender = "Male";
        string Department = "IT";

        return (EmployeeName, Salary, Gender, Department);

    }
}

The above example deconstructs the 4-tuple returned by the GetEmployeeDetails() method explicitly by declaring the types of each filed within the parenthesis.

Way2:

You can also use the var keyword so that C# infers the type of each variable. You can place the var keyword outside of the parentheses. Let us understand this by modifying the code as shown below.

class Program
{
    static void Main()
    {
        var (Name, Salary, Gender, Dept) = GetEmployeeDetails(1001);

        // Do something with the data.
        //here we are just printing the data in the console

        Console.WriteLine("Employee Details :");
        Console.WriteLine($"Name: {Name},  Gender: {Gender}, Department: {Dept}, Salary:{Salary}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (string, double, string, string) GetEmployeeDetails(long EmployeeID)
    {
        //based on the EmployyeID get the data from a database
        //here we are hardcoded the value
        string EmployeeName = "Pranaya";
        double Salary = 2000;
        string Gender = "Male";
        string Department = "IT";

        return (EmployeeName, Salary, Gender, Department);

    }
}

The above example uses type inference when deconstructing the 4-tuple returned by the GetEmployeeDetails method. You can also use the var keyword individually with any or all of the variable declarations inside the parentheses. Let us understand this with an example.

class Program
{
    static void Main()
    {
        (var Name, var Salary, string Gender, var Dept) = GetEmployeeDetails(1001);

        // Do something with the data.
        //here we are just printing the data in the console

        Console.WriteLine("Employee Details :");
        Console.WriteLine($"Name: {Name},  Gender: {Gender}, Department: {Dept}, Salary:{Salary}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (string, double, string, string) GetEmployeeDetails(long EmployeeID)
    {
        //based on the EmployyeID get the data from a database
        //here we are hardcoded the value
        string EmployeeName = "Pranaya";
        double Salary = 2000;
        string Gender = "Male";
        string Department = "IT";

        return (EmployeeName, Salary, Gender, Department);

    }
}

Note: This method is cumbersome and is not recommended.

Way3:

You may deconstruct the tuple into variables that have already been declared. Let us understand this with an example

class Program
{
    static void Main()
    {
        string Name;
        double Salary;
        string Gender = "Female";
        string Dept = "HR";

        (Name, Salary, Gender, Dept) = GetEmployeeDetails(1001);

        // Do something with the data.
        //here we are just printing the data in the console

        Console.WriteLine("Employee Details :");
        Console.WriteLine($"Name: {Name},  Gender: {Gender}, Department: {Dept}, Salary:{Salary}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (string, double, string, string) GetEmployeeDetails(long EmployeeID)
    {
        //based on the EmployyeID get the data from a database
        //here we are hardcoded the value
        string EmployeeName = "Pranaya";
        double Salary = 2000;
        string Gender = "Male";
        string Department = "IT";

        return (EmployeeName, Salary, Gender, Department);

    }
}
Points to Remember while Splitting Tuples in C#:

Note that you cannot specify a specific type outside the parentheses even if every field in the tuple has the same type. This generates compiler error CS8136, “Deconstruction ‘var (…)’ form disallows a specific type for ‘var’.”.

Note that you must assign each element of the tuple to a variable. If you omit any elements, the compiler generates error CS8132, “Cannot deconstruct a tuple of ‘x’ elements into ‘y’ variables.”

You cannot mix declarations and assignments to existing variables on the left-hand side of a deconstruction. The compiler generates error CS8184, “a deconstruction cannot mix declarations and expressions on the left-hand side.” when the members include newly declared and existing variables.

In the next article, I am going to discuss the Local Functions in C# with some examples. Here, in this article, I try to explain Splitting Tuples in C# step by step with some simple examples. 

Leave a Reply

Your email address will not be published. Required fields are marked *