Question string variable broken

GamerDevy

New member
Joined
Jan 29, 2022
Messages
1
Programming Experience
Beginner
So, I'm using this bit of code in "Visual Studio Code" and it keeps saying: "Converting null literal or possible null value to non-nullable type."

string name = Console.ReadLine();

This is the bit of code I am using and it should work fine! Please help me!
 
In .NET 5 and later, the Console.ReadLine method is declared as type string? rather than type string. Try declaring your variable using var and let the type be inferred.
 
Actually, I just did some testing in VS 2022 and determined a few things. That code did not cause any issues in a .NET 5 Console app but it was flagged as a warning in a .NET 6 Console app. I looked at the project files and the latter included the following that the former did not:
.NET 6 Console Application Project:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
I removed that line and the warning disappeared. That means that you have three potential solutions to your issue:
  • Declare the variable as type string?.
  • Declare the variable using var.
  • Remove the nullable reference type check from the project file.
 
There's also a fourth "solution" and that is to do nothing. It is just a warning - not an error - and so it won't prevent compilation. If you know that the result will never be null, which is likely the case, then you know that no exception will ever be thrown. You could explicitly ignore the warning or add a comment explaining why it's not an issue. I'm not a big fan of ignoring warnings but it is an option.
 
Could interactive console return null for ReadLine? If user just press Enter without typing text it returns an empty string and not null.
Internally ReadLine uses TextReader.ReadLine (for StreamReader), which is why it returns string? for .Net 6. A StreamReader can wrap any Stream and would return null when end of stream is reached.
Anyway, one have to deal with the nullable return sooner or later.
 
To me, using the null forgiving operator is just like using explicit casts. Most of the time, I am telling the compiler "Trust me. I know what I am doing." Other times it's like: "Hold my beer. Let me get my shotgun."
 

Latest posts

Back
Top Bottom