C#: For statement optional initialization

In the previous post, we mentioned init, expression, and update in the syntax of the for statement.  The init, expression and update are optional.

In the following for loop, the variable number is declared outside the loop, so potentially number can be used from other starting point in the code outside the for statement block.

We leave out the initialization part of the for statement as shown in the example below.

using System;

namespace Conditional
{
    static class Program
    {
        private static int max = 5;

        private static void checkNumber(int max1)
        {
            int number = 3;
            int max = max1;

            for ( ; number < max; number++)
            {
                Console.WriteLine(number);
            }
        }

        static void Main()
        {
            Program.checkNumber(max);
            Console.ReadLine();
        }
    }
}

 

Series Navigation<< C#: The for statement
C#: The break statement >>