C# While Statement

The While Statement loops a block of code if the Boolean expression is true.


while (boolexpression)
Code to execute

Tip: In the VS studio IDE, if you type while until it’s highlighted and then hit tab twice, the syntax will automatically be inserted.

Create a new C# project and name it WhileStatement and then copy the following:

 int num;
 num = 1;

 while (num < 20)

This is a very simple While Statement, it evaluates the variable num. If num is less than 20 (which it is) then increment.

Breaking from Loops / Reading a text file

It is easy to forget to break from loops, meaning the While Statement goes on and on. When breaking from loops you use the break keyword. Create a text file and save it on your desktop; make sure it has a few lines of text, a paragraph is fine. Then at the top where the using directives are, add the System.IO namespace:

using System.IO;

This brings the input/output namespace into scope, which allows us to read and write files.


   string path = @"U:\Users\Asim Rehman\Desktop\notes.txt";
   StreamReader sr = new StreamReader(path);

                string line = sr.ReadToEnd();
                while (line != null)

Make sure you change the path to the file name you created; by default it should be C:\users\your name\desktop.

Code Explained

  • First we set the path to the file name.
  • Next we use class StreamReader and also make a new variable named sr which is set to read the file to the end (path).
  • Then we create another string line which reads the file to the end.
  • We then read each line to the end (the Boolean expression means if line is NOT null, so basically ensures the text file is not empty).
  • We use the break keyword to stop the while statement once we finish reading to the end.
  • If you do not have the break keyword, the loop will continue over and over.


You can use these operators in a While Statement.

Operator Description Example
< Less than While (10 < 20)
> Greater than While (20 > 10)
<= Less than or equal to While (num <= 20)
>= Greater than or equal to While (num >= 20)
== Equal to While (num == 10)
!= Not equal to While (num != 25)


This tutorial covered the basics of the While Statement. Remember to break out of your while statements, as they will continue to loop, and the expression must be a Boolean.