C
C#16mo ago
__dil__

❔ Reading from stdin

So, I'm trying to work with basic IO stuff. I have this snippet:
string line;
while ((line = Console.ReadLine()) != null) {
// Stuff...
}
string line;
while ((line = Console.ReadLine()) != null) {
// Stuff...
}
I get a warning about assigning a nullable value to a non-nullable variable. I understand what the warning is saying, but I'm not sure how I'm supposed to do any better than this considering I am already checking for null values. Any recommendations?
7 Replies
Jimmacle
Jimmacle16mo ago
Console.ReadLine() will almost never return null, i think the only situation is if the user hits ctrl+z
Pobiega
Pobiega16mo ago
Yup, so you can silence that warning with a bang
Jimmacle
Jimmacle16mo ago
it's one of those things where it's probably okay to just suppress the warning like Console.ReadLine()!
__dil__
__dil__OP16mo ago
Noted, thank you both
Angius
Angius16mo ago
Alternatively,
Console.ReadLine() ?? "";
Console.ReadLine() ?? "";
to get an empty string instead of null
reflectronic
reflectronic16mo ago
alternatively, string? line; does not require any other code changes
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?