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
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)
{
// ...
}
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() ?? "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With