Home > Back-end >  Converting null literal for Console.ReadLine() for string input
Converting null literal for Console.ReadLine() for string input

Time:12-12

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

CodePudding user response:

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)
{
    // ...
}
  • Related