0

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?

2
  • Move Visual Studio to one side of your screen, your console window to the other side and step through the code with F10 to see why. Commented Oct 15, 2013 at 10:57
  • 2
    1) You're not closing the reader. 2) look at System.IO.File.ReadallLines(). Commented Oct 15, 2013 at 11:02

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0
 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)

1 Comment

Use of word "Empty" to explain null is likely to confuse things for a beginner as string.Empty != null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.