Reverse FOR loop in C# – A quick look

for (int i = list.Count - 1; i >= 0; i--)
{
    list[i] = 1337;
}

The reverse FOR loop in C# are useful if you need to iterate a List or array backwards. Without first having to reversing it, which can be time and memory consuming.
Therefore, by using a reversed FOR loop you can traverse a list, array or string backwards in a simple way.

So if you take a look at the examples you can see 2 versions of the reverse FOR loop in C#. Firstly, the classic way and after is a simplified way, by combining the condition and decrement of i.

for (int i = list.Length; i-- > 0;)
{
    list[i] = 1337;
}
Evolving, just backwards - PewDiePie - Reverse FOR loop in C#

The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true.

At any point within the for statement block, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement. You can also exit a for loop by the gotoreturn, or throw statements.

So why don’t you checkout these simple easy to read articles about adding objects in list, for loops and reverse for loops if you want som extra reading:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/for-loop-in-c-sharp-simple.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.

Add object to List in C# – simple and the links above. Is part of a series of easy read and quick use code examples. That you can use in your c#/.net coding!

2 thoughts on “Reverse FOR loop in C# – A quick look

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait