Search code examples
c#if-statementwhile-loopstreamreaderconsole.writeline

C#-Why does this if statment removes a new line character on StreamReader's output?


StreamReader reader = new StreamReader("randomTextFile.txt");
string line = "";

while (line != null)
{
    line = reader.ReadLine();

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

reader.Close();
Console.ReadLine();

In the above code, there is an if statment inside the while statment, even though they specify the same thing (line != null). If I remove said if statment, a new line will be added after the txt file contents (instead of "11037", the console will show "11037" + an empty line).


Solution

  • The while-loop exit condition will only be checked when it is invoked, so at the beginning of each iteration, not everytime inside it's scope.

    MSND: the test of the while expression takes place before each execution of the loop

    You could use this loop:

    string line;
    using (var reader = new StreamReader("randomTextFile.txt"))
    {
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
    

    You should also use the using-statement as shown above on every object implementing IDisposable. On that way it is ensured that unmanaged resources are disposed.


    According to the Console.WriteLine specific question why it writes a new line even if the value is null, that's documented:

    If value is null, only the line terminator is written to the standard output stream.