Search code examples
c#tuplesvaluetuple

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

  • Yes you can iterate through the Items via the following for loop:

    var tuple = ("First", 2, 3.ToString());
    ITuple indexableTuple = (ITuple)tuple;
    for (var itemIdx = 0; itemIdx < indexableTuple.Length; itemIdx++)
    {
        Console.WriteLine(indexableTuple[itemIdx]);
    }
    
    • The trick is that you need to explicitly convert your ValueTuple to ITuple
    • That interface exposes Length and index operator

    ITuple resides inside the System.Runtime.CompilerServices namespace.