C
C#2y ago
jack

❔ string with error onverting null literal or possible null value to non-nullable type.

i think the string isnt workijng and wen i use var it works but the only thing that isnt working is the varaible on the readline isnt functionng right
namespace Brack2
{
class Program
{

static void Main(string [] args)
{
Console.WriteLine("Whats ur name");

string playerName = Console.ReadLine();

Console.WriteLine("Hi " + playerName);

Console.ReadKey();
}
}
}
namespace Brack2
{
class Program
{

static void Main(string [] args)
{
Console.WriteLine("Whats ur name");

string playerName = Console.ReadLine();

Console.WriteLine("Hi " + playerName);

Console.ReadKey();
}
}
}
7 Replies
Angius
Angius2y ago
Console.ReadLine() returns a string? not a string It's due to an edge case when certain inputs can result in it not returning a string, not even an empty one, but rather returning nothing A common workaround is Console.ReadLine() ?? "" It provides a fallback, in case the readline returns null, it falls back to "", an empty string, so it always remains a string
jack
jackOP2y ago
thank u so much but does this issue happen with like int bool and float values and if it does would i use the same fix
Angius
Angius2y ago
Depends on what any given method returns It's not something related to strings, or bools, or ints It's something related to nullable types A method can return int or it can return int? It can return string? like this one, or it can return string
jack
jackOP2y ago
ok this is all good 2 know thx
Angius
Angius2y ago
In case of nullable types, yeah, you can always use a fallback nullableInt ?? 0, nullableBool ?? false, nullableChar ?? '\0' etc
jack
jackOP2y ago
ok thx
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server