C#: The do-while statement

This entry is part 44 of 71 in the series C#

The do-while statement is very similar to the while statement, except that the first loop always gets executed at least once.

Its syntax is:

do
{
    statements;
} while (expression)

The statements in the do loop will first be executed.  This is done without any condition.

The while statement in the will be executed if the expression resolves to true, similar to the while loop in the earlier example.

Do-While Loops
using System;

namespace Conditional
{
    class Program
    {
        private int number;

        private Program(int number1)
        {
            number = number1;
        }

        private void checkNumber()
        {
            int number = 0;

            do
            {
                Console.WriteLine(number);
                number++;
            } while (number < 3);
        }

        static void Main()
        {
            int x = 0;

            Program increment = new Program(x);
            increment.checkNumber();
            Console.ReadLine();
        }
    }
}

The output from running the above code is 0,1,2.

Series Navigation<< C#: Read a file and output to a second file
C#: The for statement >>