Method looping without using / foreach / while

Is there a way to call a method / lines of code several times without using a for / foreach / while loop?

For example, if I should use for a loop:

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

The lines of code that I call do not use "i", and, in my opinion, the whole loop declaration hides what I am trying to do. This is the same for foreach.

I was wondering if there is a loop that I can use that looks something like this:

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

It is clear that I just want to execute this code 6 times, and there is no noise associated with creating the index and adding 1 to some arbitrary variable.

As a training exercise, I wrote a static class and method:

Do.Multiple(int iterations, Action action)

What works, but is very much appreciated on an ambitious scale, and I'm sure my colleagues do not approve.

, , , for, , , , (). .

( , ) IEnumerable foreach

+5
4

, for , .
, , for , .

+12

, :

public static void Times(this int iterations, Action action)
{
    for (int i = 0; i < iterations; i++)
    {
        action();
    }
}
...
6.Times(() => {
    DoSomething();
    SomeProperty = true;
});

for. , .

+10

private MethodDelegate MultiMethod(MethodDelegate m, int count) {
  MethodDelegate a;
  if (count > 0) {
    a = m;
    a += MultiMethod(m, --count);
  } else {
    a = delegate { };
  }
  return a;
}

!

MultiMethod(action, 99)();
+2
source

How about do .... before or if ... then

Use the counter inside the loop and run it until it reaches 6.

Or an if-then statement using a counter. If your value is 6, exit the loop.

I am not a programmer guru, but if you have an action that needs to be performed a certain number of times, a counter will be needed somewhere, regardless of whether it is a function of your loop or if it is created using a counter.

0
source

All Articles