'Number and type of elements in System.ValueTuple

I was looking for an alternative to a local structure in C#, which is possible in C/C++ but not possible in C#. That question introduced me to the lightweight System.ValueTuple type, which appeared in C# 7.0 (.NET 4.7).

Say I have two tuples defined in different ways:

var book1 = ("Moby Dick", 123);
(string title, int pages) book2 = ("The Art of War", 456);

Both tuples contain two elements. The type of Item1 is System.String, and the type of Item2 is System.Int32 in both tuples.

How do you determine the number of elements in a tuple variable? And can you iterate over those elements using something like foreach?

A quick reading of the official documentation on System.ValueTuple doesn't appear to have the information.



Solution 1:[1]

I guess what you're looking for is something like this:

    public void Run(string[] args)
    {
        Tuple<string, string, int> myTuple = new Tuple<string, string, int>("1st", "2nd", 3);
        LoopThroughTupleInstances(myTuple);
    }

    private static void LoopThroughTupleInstances(System.Runtime.CompilerServices.ITuple tuple)
    {
        for (int i = 0; i < tuple.Length; i++)
        {
            Console.WriteLine($"Type: {tuple[i].GetType()}, Value: {tuple[i]}");
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nic71