Do While loop in CSharp
The difference between While loops and Do While loops is that they run the block once, even if the condition is not met.
The best way to do explain this is by using an example:
Example of Do While loop in CSharp
public class Panjutorials { public static void Main(string[] args) { int counter=1; do{ Console.WriteLine(counter); counter++; }while(counter<10); Console.Read(); } }
If you run this code it will output 1 to 9. This is nothing new. So far it is the same as the while and the for loop. Now what differentiates the do while loop from the other loop types:
public class Panjutorials { public static void Main(string[] args) { int counter=20; do{ Console.WriteLine(counter); counter++; }while(counter<10); Console.Read(); } }
Although the condition in the brackets is not met, the block is still executed once. It will output 20. So you see, the condition is only asked once. This can be especially useful when writing more complex programs where it is not as obvious as here. If you simply do not know beforehand whether the condition will be met or not, but you still want at least to run the code once.