Reputation: 1686
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
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
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
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
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