I'm relatively new to coding, and brand new to C#. I'm working through the Channel 9 tutorials on MSDN and I've run across something I don't understand involving Console.ReadLine().
As part of one of the tutorials, the instructor produced the following code:
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("Values.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
{
Console.WriteLine(line);
}
}
myReader.Close();
Console.ReadLine();
}
This code works--it reads a series of numbers, each on its own line, from Values.txt and then sends them to the console window. My question is WHY it works. It's my understanding that Console.ReadLine() reads a single line from the input stream. But in this case, it's reading several lines despite not being part of the while loop. I would have expected that, as written, the console window would only display the last line of Values.txt, and that Console.ReadLine() would have to follow Console.WriteLine(line) within the if statement in order to display all lines. What am I not understanding? Thanks for the help!
Console.WriteLine() is the command that outputs to the console window, and since it's part of the while loop. It prints every line from the file.
Console.ReadLine() at the end here, is only added to force the debug console window to stay open until user inputs and hits enter, usually for this case Console.ReadKey() is more appropriate. But in the above code, Console.ReadLine() is not the code that reads numbers from the file. It's myReader.ReadLine(); in the while loop. So the while loop, keeps reading lines from the file until it gets to the end of file.