Home > Mobile >  Console.ReadLine() showing "Converting null literal or possible null value to non-nullable type
Console.ReadLine() showing "Converting null literal or possible null value to non-nullable type

Time:01-30

New to C#. I am trying this code, which I copied from w3school User Input

using System;
 
namespace Sample
{
    class Test
    {
        public static void Main(string[] args)
        {
            string testString;
            Console.Write("Enter a string - ");
            testString = Console.ReadLine();
            Console.WriteLine("You entered '{0}'", testString);
        }
    }
}

But after I execute the Program, it shows an error at Console.ReadLine();

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

CodePudding user response:

you need to handle nullable try to replace

string testString;

with

string? testString = null;

or

string testString="";

In the declaration of testString, take note of the ? symbol that has been added after the data type. This shows that the variable can have a null value, which means it is nullable.

CodePudding user response:

In recent versions of .NET, nullable reference types are supported by default and Console.ReadLine returns a nullable string. That means that you need to either declare your variable as nullable:

string? testString;

or specify that the return value will definitely not be null:

testString = Console.ReadLine()!;

If you use the former, you'll have allow for that when you use the variable later. The latter is OK because, in a console window, it will never be null.

You ought to do some reading on nullable reference types.

CodePudding user response:

You need to make sure that you have a valid non-null string.

You could do this for example to make sure that it's valid before printing it to the console using the formatter:

testString = Console.ReadLine() ?? string.Empty;

This will assign an empty string to the testString variable in case that ReadLine() returns null.

  • Related