C# > Core C# > Control Flow > while Loop
Basic While Loop Example
This snippet demonstrates a basic while loop that iterates as long as a given condition is true. The loop prints the current value of a counter variable until it reaches a specified limit.
Code Sample
The code initializes a counter variable to 0 and a limit variable to 5. The while loop continues to execute as long as the counter is less than the limit. Inside the loop, the current value of the counter is printed to the console, and then the counter is incremented. Once the counter reaches the limit, the loop terminates, and a message is printed to indicate that the loop has finished.
using System;
public class WhileLoopExample
{
public static void Main(string[] args)
{
int counter = 0;
int limit = 5;
while (counter < limit)
{
Console.WriteLine("Counter value: " + counter);
counter++;
}
Console.WriteLine("Loop finished!");
}
}
Concepts Behind the Snippet
The while loop is a fundamental control flow statement in C#. It repeatedly executes a block of code as long as a specified boolean condition is true. The condition is evaluated before each iteration. If the condition is initially false, the loop body will not execute at all.
Real-Life Use Case
A common use case for while loops is processing data from a stream or a file. For example, you might read lines from a file until you reach the end of the file, or process messages from a queue until the queue is empty. Another example is polling an external resource (like a database or an API) until a specific state is reached.
Best Practices
Always ensure that the condition controlling the while loop will eventually become false to avoid infinite loops. Carefully consider the initial value of variables used in the condition, and make sure the loop body modifies these variables in a way that progresses towards the termination condition. Use descriptive variable names for better readability.
Interview Tip
Be prepared to explain the difference between while and do-while loops. The key difference is that a do-while loop executes its body at least once, even if the condition is initially false. In contrast, a while loop might not execute its body at all.
When to Use Them
Use while loops when you want to repeat a block of code an unknown number of times, based on a condition that is evaluated before each iteration. Choose while over for when the number of iterations is not known in advance or is based on a dynamic condition.
Alternatives
For a fixed number of iterations, a for loop is generally more suitable and readable. For iterating over collections, a foreach loop is often the best choice. Recursive functions can sometimes provide an alternative to loops, although they should be used with caution to avoid stack overflow issues. For asynchronous operations, consider using async/await and task-based concurrency patterns instead of blocking loops.
Pros
while loops are flexible and can handle complex conditions. They are well-suited for situations where the number of iterations is not known beforehand.
Cons
If the loop condition is not carefully managed, while loops can easily lead to infinite loops, which can crash your application. They can sometimes be less readable than for or foreach loops when the number of iterations is known in advance.
FAQ
-
What happens if the condition in a
whileloop never becomes false?
If the condition in awhileloop never becomes false, the loop will continue to execute indefinitely, resulting in an infinite loop. This can cause your application to freeze or crash. Make sure that your loop condition will eventually evaluate to false. -
What is the difference between a
whileloop and ado-whileloop?
The main difference is that awhileloop checks the condition before each iteration, while ado-whileloop checks the condition after each iteration. This means that ado-whileloop will always execute at least once, even if the condition is initially false.