Search This Blog

Friday, January 6, 2012

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 it works using Reflection.. Well, it's not, there are some hooks in a language itself for this construct. Btw, foreach loop is 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 :)).

No comments:

Post a Comment