Looping through a method without for/foreach/while

Posted by RichK on Stack Overflow See other posts from Stack Overflow or by RichK
Published on 2010-03-17T13:26:52Z Indexed on 2010/03/17 13:31 UTC
Read the original article Hit count: 177

Filed under:
|

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) http://stackoverflow.com/questions/2248985/using-ienumerable-without-foreach-loop

© Stack Overflow or respective owner

Related posts about c#

Related posts about for-loop