The while
operator iterates over a block of code until the conditional query equals false or the code is interrupted with a goto
, return
, break
or throw
statement.
Syntax for while
keyword:
while( condition ) { code block; }
Example:
int i = 0;
while (i++ < 5)
{
Console.WriteLine("While is on loop number {0}.", i);
}
Output:
"While is on loop number 1."
"While is on loop number 2."
"While is on loop number 3."
"While is on loop number 4."
"While is on loop number 5."
A while loop is Entry Controlled, as the condition is checked before the execution of the enclosed code block. This means that the while loop wouldn't execute its statements if the condition is false.
bool a = false;
while (a == true)
{
Console.WriteLine("This will never be printed.");
}
Giving a while
condition without provisioning it to become false at some point will result in an infinite or endless loop. As far as possible, this should be avoided, however, there may be some exceptional circumstances when you need this.
You can create such a loop as follows:
while (true)
{
//...
}
Note that the C# compiler will transform loops such as
while (true)
{
// ...
}
or
for(;;)
{
// ...
}
into
{
:label
// ...
goto label;
}
Note that a while loop may have any condition, no matter how complex, as long as it evaluates to (or returns) a boolean value (bool). It may also contain a function that returns a boolean value (as such a function evaluates to the same type as an expression such as `a==x'). For example,
while (AgriculturalService.MoreCornToPick(myFarm.GetAddress()))
{
myFarm.PickCorn();
}