Foreach loop – eligible types

Apparently, the types are not required to implement IEnumerable to be iterated over with foreach loop – they just required to have GetEnumerator() method.

 

class EnumerableItem
{
}

class EnumerableItemsCollection // : IEnumerable<EnumerableItem>
{
    public IEnumerator<EnumerableItem> GetEnumerator()
    {
        return null;
    }
    public static void Test()
    {
        foreach (var item in new EnumerableItemsCollection())
        {
        }
    }
}

The code above compiles just fine.
My first thought was – “Reflection ?”. Can’t be, Reflection is too slow. It is, in fact, handled by compiler.

First, it checks if the type can be implicitly converted to an IEnumerable; if it can’t – it will look for a GetEnumerator method.

Also, the foreach loop calls for Dispose on enumerated object, so using using on it is redundant.

Btw, for some reason foreach loop seems to be a bit faster than for loop (not by much, and they’re both very fast.. don’t switch for loops to foreach to speed up your code :)).

 

For references, check the C# language specs document.

Leave a Reply

Your email address will not be published. Required fields are marked *