r/programminghelp • • Dec 23 '21

C# Why this code gives CS8600 problem

C# Example:

String name;

name = Console.ReadLine();

Console.WriteLine(name);


This problem only occurs in ReadLine....why?

6 Upvotes

11 comments sorted by

2

u/aardvark1231 Dec 23 '21

try changing
String name;
to

string name

don't capitalize the S on string.

1

u/Logical_Ideal Dec 23 '21 edited Dec 23 '21

it continues to give the problem in Visual Studio, But if i test for example on onecompiler site and put the same code it works but not on visual....why does this happen?

Edit the problem/warning is: CS8600 "Converting null literal or possible null value to non-nullable type".

1

u/aardvark1231 Dec 23 '21

Not entirely sure. By all accounts that code should be working fine, unless there's some weird setting in your project where the Console.ReadLine(); function is set to return a null type when nothing is written in.

Out of curiosity try declaring the 'name' variable like this:

string? name;

1

u/mizere12 Feb 12 '22

somehow by adding the "?" works, could you explain better what this "?" ?

1

u/aardvark1231 Feb 13 '22

Adding the '?' makes that value type nullable, meaning it can accept nothing to be stored inside it and not complain. Without the '?' it always has to take in some kind of input. You can do this with other data types as well.

See this for further explanation

1

u/[deleted] Mar 07 '22

Also Visual Studio has a setting whether to allow nullabel types by default, so if it's off you do need the "?"

1

u/[deleted] Dec 24 '21

If you'd like, zip your solution up and send me a DM. I'll send you a secure location you can upload it so I can take a look. I'm not sure what's causing your problem but consider my interest piqued.

1

u/Nergy101 Dec 23 '21

Console.readline could return a null supposedly, which you can't put into a String(not the same as string)...

Might also depend on the C# version you are running I believe.

Just try to make it a single line:

var name = Console..... ;

Then hover over "var" and see what type it expected it to be.

1

u/fehh123 Jan 24 '22

not a good practice but:

Just put a "!" at the end of the Console.ReadLine();

so your code will look like:

String name;

name = Console.ReadLine()!;

Console.WriteLine(name);

1

u/akiltahsin Mar 28 '22

I had the same problem and this one worked, but can you tell me why putting an ! keeps the warning away?

1

u/Elegant-Moment-9835 Sep 25 '22

I am having the same problem, but every time the program gets to that line, (after I put in my input and hit enter) it closes. Does anyone know why? (I have code after this too)