How to use Tuple elements in C# (C Sharp)

Tuples in C# are one of the best features. I assume you already know – what are tuples and How to declare tuples in c#. Now it’s time to learn about How to use tuple elements in c#.

How to read multiple values from Tuple in c# –

Let’s open Visual Studio and create a console application. This is my quite simple Program class.

class Program
{
    static void Main(string[] args)
    {
        (string, int) personTuple = ("Nitish", 1);
    }
}

Here, I have created a simple tuple with two values. Now it’s time to read the values from this tuple.

In the next line of your code, write the personTuple variable, press dot/period (.), then you will see that this variable contains two fields (Item1 & Item2).

Get tuple elements in c#
How to get tuple elements in c#

These Item1 & Item2 represent the type that we have defined in our tuple type. Here is the mapping of Item1 & Item 2 with the tuple –

Get tuple elements in c#

Here you can notice that Item1 represents the first element string . And the Item2 represents the second element int.

If you will add three elements in the tuple then here you will find Item1, Item2 & Item3, and so on.

Print the Tuple elements –

Let’s use the WriteLine method to display the values of Tuple.

class Program
{
    static void Main(string[] args)
    {
        (string, int) personTuple = ("Nitish", 1);

        Console.WriteLine($"First element  - {personTuple.Item1}");
        Console.WriteLine($"Second element - {personTuple.Item2}");

        Console.ReadLine();
    }
}

Time to run the application and here is the output –

Display tuple elements in c#
Output

How to use Tuple in c# method –

Let’s create a new method GetPersonDetails in our console application.

public static (string, int) GetPersonDetails()
{
    return ("Nitish", 1);
}

We can call this method in our Main method and use the elements.

class Program
{
    static void Main(string[] args)
    {
        (string, int) personTuple = GetPersonDetails();

        Console.WriteLine($"First element  - {personTuple.Item1}");
        Console.WriteLine($"Second element - {personTuple.Item2}");

        Console.ReadLine();
    }

    public static (string, int) GetPersonDetails()
    {
        return ("Nitish", 1);
    }
}

Again, run the application and you will get both the elements on your console screen.

Display tuple elements in c#
Output

Books To learn C#