#CSharp Question

1 messages · Page 1 of 1 (latest)

grizzled yew
#

I you hover the line, it will tell you what is wrong.
Generally speaking, green lines indicate warnings; they won't stop your code from running but may imply what could/should be improved.

In this case, the reason for the warning likely is, that the type returned by Console.ReadLine (string) can be null - which can lead to runtime exceptions in some cases. Since you have not told the code that it is okay for the value to be null here, you get a warning.

To get rid of the warning, either

  • disable "Nullable" in the project settings
    or
  • tell the code that a null value will not be an issue here, by placing an exclamation mark at the end of the method call: string userName = Console.ReadLine()!;
bleak leaf
#

Okay, thanks for the explanation!

void void
#

disable "Nullable" in the project settings
This is generally a bad idea. It's enabled by default for good reason

void void
# bleak leaf Okay, thanks for the explanation!

The third option is to declare the variable as nullable, i.e. changing the type from string to string?.

However, in the case of Console.ReadLine and only Console.ReadLine, you can indeed suppress it using Zenvin's second suggestion (using the null-forgiving operator, !, after the expression) because there is only one situation in which this method returns null, and that's when the standard input stream has closed - which only happens when the application has quit. Since the application is closed at that point, it won't ever actually see ReadLine returning null, and so it's safe to suppress it here

#

In about 95% of other cases, you shouldn't shut the analyzer up with ! (there are few exceptions to this, but they're very edge case and you shouldn't worry about them for a while, since you are obviously new to C#. You can learn about that later)