Imagine you have to delete a bunch of items from a list, something like this:
Will it work? Of course not because you are removing items while your are looping the entire list. That means sooner or later you’ll bump against out of index exception or items silently won’t be removed. And this is a common mistake we all do I suppose.
The solution is a pretty easy one – reverse the for loop, like this:
However I find writing reverse loops harder than the former one. Not sure why but I guess that’s how I am used to do the maths – addition is always easier compared to subtraction.
Luckily there is CodeRush to the rescue. Just execute the Reverse For Loop code reformatting (not refactoring because you do change the meaning of the code with this one) and you are done.
It works the other direction as well. Until today I didn’t even know that this trick exists. I just assumed it does and it sure did exist. This and a “million” of other features makes CodeRush really a must have coding tool.