I was wondering, when exactly can I use the foreach loop? Do I have to implement IEnumerable?
You can foreach though any object that implements IEnumerable
or IEnumberable<T>
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.
Comprehensive explanation: http://msdn.microsoft.com/en-us/library/aa664754%28VS.71%29.aspx
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.