The Average Joe For-Loop
We have a method and we want to execute it a certain number of times. Say, 10 times. We can easily write a
for-loop that iterates
10 times and it’s all good.
The Normal Way
This is perfectly fine and gets the job done. But, and that but is the whole reason for this post,
for loops often come with those pesky boundary conditions. You can easily make a mistake with the initialization and set it to
1, or maybe you messed up the condition and set it to
i <= 10. Something like that. So what if there’s a way to eliminate the need to write those conditions and simply specify how many times do you want the loop to iterate? Well, we’re in luck.
Extension Methods to the Rescue!
We can write an extension method on
int, where it will iterate the number of times we want. We pass an
Action() to the method, so you can execute whatever the method you want.
Then call it like this:
You can simply call the extension method on an
int (either literal or a variable), so there’s not much mistaking.
Now that wasn’t too bad, but what if we need access to the iterator. Say our
SayHello() method looks like this:
Then we can’t use the above method, but don’t worry, all is not lost.
Let’s turn to For-Each
Then we can make use of
Look at Documentation for the
Range() method. First parameter is the
Starting Integer and the second is the
Count. So the above code sample would start at
0 and run
The following would iterate
4 times, from