16 Replies
check the return type on
Console.ReadLine
it returns a string?
correct:
string?
meaning a nullable string
so it might be null
and calling input.All
on null would do what?ah i see
sorry if this is a dumb question, but is there any way to remove the warning
certainly
!
input = Console.ReadLine()!;
for specifically readline, this is fine, since the only time it returns null is... a very specific scenarioThanks a ton
in most cases, using
!
to silence a null warning is... problematic
you are just hiding what can likely be an error
also, this entire method can be greatly simplified, if you are interested?Console.ReadLine() ?? ""
would probably be more idiomatic than !
I simply put the ! directly after input on the if statement
is there something major that I am missing?
this is how I would write this method
if you dont care about giving two different error messages, you can combine them again
I just prefer to split it like this
but the removal of the
needName
and inlining the return inside the loop is... just easieroh yeah, im pretty sure that I started this with the intention of having the input be an out string
but since i changed from that this is much better
also, note how I didn't need to do any
!
to remove the null warning
since we check string.IsNullOrWhitespace
šah
Thanks a ton, this is really helpful
the warning disappears if you start your if statement with the null check first, because it assumes that if it's true the 2nd boolean statement doesn't have to be checked.
but in general Pobiega's response is better, because it provides more details on the user regarding what went wrong
CTRL+Z, right? Sounds like it would be worth to check for
null
as you did in the final solution :blobthumbsup:yeah ctrl+z or if the input is redirected, so its pretty rare. I agree that its better to actually check for the null (since you can effectively treat it as "no input")