Search code examples
loopsforeachlanguage-agnostic

Why should I use foreach instead of for (int i=0; i<length; i++) in loops?


It seems like the cool way of looping in C# and Java is to use foreach instead of C style for loops.

Is there a reason why I should prefer this style over the C style?

I'm particularly interested in these two cases, but please address as many cases as you need to explain your points.

  • I wish to perform an operation on each item in a list.
  • I am searching for an item in a list, and wish to exit when that item is found.

Solution

  • Two major reasons I can think of are:

    1) It abstracts away from the underlying container type. This means, for example, that you don't have to change the code that loops over all the items in the container when you change the container -- you're specifying the goal of "do this for every item in the container", not the means.

    2) It eliminates the possibility of off-by-one errors.

    In terms of performing an operation on each item in a list, it's intuitive to just say:

    for(Item item: lst)
    {
      op(item);
    }
    

    It perfectly expresses the intent to the reader, as opposed to manually doing stuff with iterators. Ditto for searching for items.