7

I noticed that ReSharper suggests me to check Console.ReadLine() for null. I don't understand why, because as far as I know the method returns "" even if you press enter in a console and don't enter any symbol.

I use VS 2015 with the 3rd update, C# 6, .NET 4.6.1, ReSharper 10.

enter image description here

user2216
  • 809
  • 1
  • 8
  • 24

3 Answers3

10

The documentation specifies that returning null is part of the contract for this method:

The next line of characters from the input stream, or null if no more lines are available.

And goes onto give an example:

If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null.

As a further example, you can change the TextReader used for Console.In using Console.SetIn. Your TextReader could return null when ReadLine is called.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
7

Console.ReadLine() can be null if you enter Ctrl + Z.

MSDN documentation:

If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the ReadLine method is called in a loop.

diiN__________
  • 7,393
  • 6
  • 42
  • 69
0

According to MSDN, if you have redirected standard input to be from a file, Console.ReadLine() will return null when there are no lines remaining to be read from the file.