AlainD
AlainD

Reputation: 6597

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.

Upvotes: 0

Views: 792

Answers (2)

Peter Csala
Peter Csala

Reputation: 22714

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.

Upvotes: 5

Nic71
Nic71

Reputation: 31

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]}");
        }
    }

Upvotes: 1

Related Questions