Implement GetEnumerator for ITuple type objects to be used in foreach

Viewed 146

So I had to refactor some code and now I'm trying to iterate to some ITuple objects and add them to a list as you could see below.

       //for the case when we have an object of type IList this works
            if (obj is IList) {
            var list = new List<GuiValue>();
            foreach (var o in (IList)obj) {
                list.Add(MethodResultToGuiValue(o));
            }
            return new GuiValue.GV_list(list);
        }
        // this is what I'm interested to solve
        if (obj is ITuple) {
            var list = new List<GuiValue>();
            foreach (var o in (ITuple)obj) {
                list.Add(MethodResultToGuiValue(o));
            }
            return new GuiValue.GV_tuple(list);
        }

So the problem that I have it's clear:

enter image description here

Type 'System.Runtime.CompilerServices.ITuple' cannot be used in 'foreach' statement because ie neither implements 'IEnumerable' of 'IEnumerable',nor has suitable 'GetEnumerator' method which return type has 'Current' property and 'Move' method.

I did exactly what it was suggested, created a new class TupleExtensions.cs, and made the extension method in order to do that.

internal static class TupleExtensions {

    internal static IEnumerable GetEnumerator(this ITuple tuple) {
        return tuple.GetType()
            .GetProperties()
            .Select(property => property.GetValue(tuple));
    }
}

But I'm still getting the above-mentioned error.

1 Answers

If you want to "iterate" through the ItemX properties, you can't just do

foreach (var o in (ITuple)obj)

since ITuple does not implement IEnumerable. However, you can do the following

if (obj is ITuple tuple) // Minor improvement to keep the result of the cast
{
   // .....
   foreach (var o in tuple.GetEnumerator()) // Explicitly get the IEnumerable
   {
     // ......
   }
   // rest of your code
}
Related