Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a method without for/foreach/while

Tags:

c#

for-loop

Is there a way of calling a method/lines of code multiple times not using a for/foreach/while loop?

For example, if I were to use to for loop:

int numberOfIterations = 6;
for(int i = 0; i < numberOfIterations; i++)
{
   DoSomething();
   SomeProperty = true;
}

The lines of code I'm calling don't use 'i' and in my opinion the whole loop declaration hides what I'm trying to do. This is the same for a foreach.

I was wondering if there's a looping statement I can use that looks something like:

do(6)
{
   DoSomething();
   SomeProperty = true;
}

It's really clear that I just want to execute that code 6 times and there's no noise involving index instantiating and adding 1 to some arbitrary variable.

As a learning exercise I have written a static class and method:

Do.Multiple(int iterations, Action action)

Which works but scores very highly on the pretentious scale and I'm sure my peers wouldn't approve.

I'm probably just being picky and a for loop is certainly the most recognisable, but as a learning point I was just wondering if there (cleaner) alternatives. Thanks.

(I've had a look at this thread, but it's not quite the same) Using IEnumerable without foreach loop

like image 744
RichK Avatar asked Mar 17 '10 13:03

RichK


1 Answers

Actually, the for loop does not hide what you're trying to do.
Anyone reading your code is already familiar with standard for loops and will understand instantly what you're doing.

like image 123
SLaks Avatar answered Oct 05 '22 12:10

SLaks