What C#’s For is For…

Reading Time: < 1 minute

Ever wondered why C# uses such a silly format for its for loop?

I mean why not do it like Pascal?

 
    var loopVar:int;
    for loopVar := 0 to 10 do
    begin
        writeln('something erudite');
    end;

Whereas C, C#, and C++ use constructs like…

    int i;
    for(i = 0; i < 10; i++)
    {
        Console.WriteLine("something erudite");
    }

The reason is not always taught in C / C# /C++ 101 and it’s really quite useful. C’s for loop is split into 3 sections.

  1. Initialisation. Here you set up the start conditions for your loop.
  2. Comparison. The loop will continue to iterate whilst the condition here evaluates to true.
  3. Loop action. An action that is performed every time the loop iterates.

You do not have to initialise an ordinal type, you do not have to use a numeric comparison, you do not have to increment or decrement anything. Today I needed to walk an exception stack, I used a for loop, roughly (but not exactly) like this.

catch(Exception ex)
{
    for (Exception subject = ex; null != subject; subject = subject.InnerException)
    {
        if (subject is ArgumentNullException)
        {
            ///do stuff
        }
    }
}

This is just a simple example, there are all sorts of places where the C style for construct comes in useful – a friendly word of advice though, don’t go nuts. If the operations that you need to perform in order to run the loop don’t neatly fit into the for loop construct, then you should probably do it a different way, else your code is likely to become difficult to read and buggy.