views:

197

answers:

4

I was wondering, when exactly can I use the foreach loop? Do I have to implement IEnumerable?

+2  A: 

You can foreach though any object that implements IEnumerable or IEnumberable<T>

Martin Harris
+23  A: 

Hi,

There is no need to implement the IEnumerable interface to use the foreach statement. Here is a quote from the MSDN (http://msdn.microsoft.com/en-us/library/9yb8xew9.aspx):

In C#, it is not absolutely necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach. As long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of enabling you to define the return type of Current to be more specific than Object, which provides type-safety.

DevExpress Team
Like this one because it correctly states that `IEnumerable` is *not* required. It certainly makes life easier, though.
Anthony Pegram
That's really interesting, and I didn't know that. But I'd assume this was mainly to support type safety in .NET 1.0. I'd say the best way to ensure type safety nowadays is to use the generic version of IEnumerable.
Martin Harris
+1 Nice detailed second paragraph.
Kyle Rozendo
+1 Learning something new every day.
BoltClock
Good point. I didn't know that either.
Zafer
Does the foreach statement is a kind of syntactic sugar? Meaning, does the compiler complies it into a "regular" 'for' statement that uses GetEnumerator().MoveNext() and Current property?
Josh
@Josh: Yes, it is sugar. No, it's not turned into a `for` loop. See the language spec: http://msdn.microsoft.com/en-us/library/aa664754%28VS.71%29.aspx
Anthony Pegram
+2  A: 

Comprehensive explanation: http://msdn.microsoft.com/en-us/library/aa664754%28VS.71%29.aspx

Jerome
+2  A: 

Ask yourself - do you really need a loop counter

The rule of thumb I use is determining if I am moving data between two indexed containers, where I really do need an index value to address the destination, or more generally, 'do I need an index count for each item I am processing in the loop' ? In those cases, I use a for loop, in pretty much all other cases (where foreach can deal with the container, which as noted above is pretty much every container) - the reason is pretty simple, it looks pretty stupid to use foreach and then have to go to the trouble of manually maintaining a loop counter.

Mark Mullin