skywalker2909
skywalker2909

Reputation: 1686

C# While loop logic

Take a look at this code below, i completely understand what this program is doing but there is one doubt regarding the output of the program on the console.

using System;
using System.IO;

class program
{
public static void Main()
{
    StreamReader myReader = new StreamReader("TextFile1.txt");
    string line = "";

    while (line != null)
    {
        line = myReader.ReadLine();
        if(line != null)
            Console.WriteLine(line);
    }

    Console.ReadLine();
}
}

and the output as follows

enter image description here

My question is that when i comment off the 'if' statement within the while loop, output is still exactly the same but the cursor moves an extra line down further, and i didn't understand why?

Upvotes: 0

Views: 216

Answers (3)

Jenson M John
Jenson M John

Reputation: 5699

 if(line != null)

prints only when string is not NULL

  //if(line != null)

prints even when string is NULL (The reason why the cursor moved to an extra line down further)

Upvotes: 0

Paddyd
Paddyd

Reputation: 1870

This is effectively what you have when you comment out the if statement

while (line != null)
{
    line = myReader.ReadLine();        
    Console.WriteLine(line);
}

So the extra line you are seeing is line being printed when it is in fact null.

When the if statement is included, WriteLine is not called on the final pass of the loop.

Upvotes: 2

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

Because last readed line is null and when you have if you don't do Console.WriteLine and you don't have additional new line.

When you commet it out you don't check if line is not null and if it is null you print new line without any other data because line=null

Upvotes: 7

Related Questions