Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting null literal for Console.ReadLine() for string input

I am new to c# so i need some guidance with this.

string NumInput = Console.ReadLine();

in my code, this statement gives the warning of

converting null literal or possible null value to non-nullable type.

Is there any alternative to this code line or anything which can make this warning disapear

like image 447
Shehzad Adeel Avatar asked Mar 26 '26 18:03

Shehzad Adeel


2 Answers

Firstly, you are seeing this message because you have the C# 8 Nullable reference type feature enabled in your project. Console.ReadLine() returns a value that can be either a string or null but you are using it to set a variable of type string. Instead either use the var keyword which will implicitly set your variable to the same type as the return value or manually set your variable as type nullable string string?. the ? denotes a nullable reference type.

You may then want to check that your variable does infact hold a string before you use it:

string? NumInput = Console.ReadLine();
if (NumInput == null)
{
    // ...
}
like image 167
Sean McCafferty Avatar answered Mar 29 '26 06:03

Sean McCafferty


Another simple way to get rid of the error is to use the null-coalescing operator (??) to assign numInput with an empty string if ReadLine() returns null:

string numInput = Console.ReadLine() ?? "";
like image 29
tronman Avatar answered Mar 29 '26 08:03

tronman