Home > Mobile >  Confused with Console.ReadLine() value in .NET 6.0. while press the [Enter] without any other input
Confused with Console.ReadLine() value in .NET 6.0. while press the [Enter] without any other input

Time:12-08

I am writing a console app with some basic function to let user have input and react based on user input. In previous(.net 3.1), I can do things like this:

string str=Console.ReadLine();
if(str==""){
     Console.WriteLine("do this");
}
else {
     Console.WriteLine("do that");
}

Since this is a new OS I just try to install .net-6.0 without thinking too much. But, due to some update in .net-6.0, the return type of Console.ReadLine() is now string? which is nullable and the code will become as follow:

string? str=Console.ReadLine();
if(str==""){
     Console.WriteLine("do this");
}
else {
     Console.WriteLine("do that");
}

Since I want to get input from user I can ignore the warning here to use the same coding as .net3.1, will the string? str=Console.ReadLine() be null and cause nullreference exception. Or in what cause I can generate null from Console.ReadLine();

CodePudding user response:

Console.ReadLine() returns null when the input is coming from a piped / redirected STDIN (rather than the interactive console), and the redirected stream reaches the end; as such, Console.ReadLine() can return null, and always could.

What you're seeing is a c# 8 feature: nullable reference types - where string? simply formalizes this to mean "a string reference that we anticipate to be null", as opposed to string which means "a string reference that should never be null". The key point here is: the return did not change - simply: the compiler is now recognizing that null is a possibility that you should consider.

The following program will take a piped input, read it to the end, and write the number of lines found:

int count = 0;
while (Console.ReadLine() is not null) count  ;
Console.WriteLine(count);

when used, for example (from cmd):

MyExe < somefile

However, when used in an interactive terminal: it will never end until you hard kill it with ctrl c

CodePudding user response:

According to the documentation of Console.ReadLine, the method only returns null if no more input is there:

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

Nevertheless, it's good to check for null anyway:

string? str=Console.ReadLine();

if (string.IsNullOrEmpty(str))
{
     Console.WriteLine("do this");
}
else
{
     Console.WriteLine("do that");
}

Alternately if you are absolutely sure there won't be null, just use ! (null-forgiving) operator

  • Related