Search code examples
c#stringintconsole.readline

Why does Read interfere with ReadLine?


I wrote a very basic program in C#. However, I don't understand the behavior of the executed program. Why does Read() interfere with ReadLine()?

int str = Console.Read();
string str1 = Console.ReadLine();

Console.WriteLine(str);
Console.WriteLine(str1);

Solution

  • The first method you are calling is Read which returns one character. But it blocks until you hit the Enter key.

    From MSDN:

    The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

    Then you call ReadLine which returns a line.

    When you hit the Enter key the Read method will return the first character and remove it from the input stream. The following call to ReadLine will then immediately return the rest of the line.

    Please note that if you enter a number Read will not return the number but the ASCII representation of the digit (49 for '1' etc.). If you are interested in getting an integer you should use ReadLine and use int.TryParse on the return value.

    If you are interested in a single key you should prefer ReadKey as it only blocks for a single key.