c#   programming practices   for-loop   iteration


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

static void Main(string[] args)
{
    for (int i = 0; i < 10; i++)
    {
        SayHello();
    }
}

public static void SayHello()
{
    Console.WriteLine("Hello!");
}

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.

public static class Ext
{
    public static void DoItXTimes(this int count, Action action)
    {
        for (int i = 0; i < count; i++)
        {
            action();
        }
    }
}

Then call it like this:

static void Main(string[] args)
{
    10.DoItXTimes(() => SayHello());
}

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:

public static void SayHello(int count)
{
    Console.WriteLine("{0} Hello!", count);
}

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 foreach.

foreach (var i in Enumerable.Range(0, 10))
{
    SayHello(i);
}

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 10 times.

The following would iterate 4 times, from 3 to 6.

foreach (var i in Enumerable.Range(3, 4))
{
    SayHello(i);
}