Reversing for loops with CodeRush

Imagine you have to delete a bunch of items from a list, something like this:

List<int> items = new List<int>();
...
for (int i = 2; i < items.Count; i++)
{
items.RemoveAt(i);
}

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:

for (int i = items.Count - 1; i >= 2; i--)
{
items.RemoveAt(i);
}

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.

cr

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.

Loading