C
C#2y ago
bialasik__

❔ Dereference of a possibly null reference.

do {
try {
choice = char.Parse(Console.ReadLine().ToUpper()); // <<< this line throws the warning

switch (choice) {
case 'P':
Console.WriteLine("Ok");
break;
case 'Q':
Environment.Exit(0);
break;
default:
Console.Write("Try again: ");
break;
}
}
catch (Exception) {
Console.Write("Try again: ");
}
}
while (choice != 'P' || choice != 'Q');
do {
try {
choice = char.Parse(Console.ReadLine().ToUpper()); // <<< this line throws the warning

switch (choice) {
case 'P':
Console.WriteLine("Ok");
break;
case 'Q':
Environment.Exit(0);
break;
default:
Console.Write("Try again: ");
break;
}
}
catch (Exception) {
Console.Write("Try again: ");
}
}
while (choice != 'P' || choice != 'Q');
11 Replies
bialasik__
bialasik__OP2y ago
i tried setting the char choice = ' ', but i still get it and cannot find solutions online
Servator
Servator2y ago
Console.ReadLine() returns string?
Servator
Servator2y ago
Servator
Servator2y ago
But you are trying to parse with char
bialasik__
bialasik__OP2y ago
yh i do this in vs2022 and i get no warning, but when i had to switch to vscode it throws this i normally do char.Parse and never get that warning in vs2022
Servator
Servator2y ago
oh you are talking about warning ReadLine() returns string? ? indicates its nullable You need to handle null situation or just tell the compiler dont worry about that with null forgive operator
char.Parse(Console.ReadLine()!.ToUpper());
char.Parse(Console.ReadLine()!.ToUpper());
! tells the compiler "I'm sure it's not null don't worry about it"
bialasik__
bialasik__OP2y ago
ahhh never knew about that operator thank you
333fred
333fred2y ago
I would generally advise you try not use the ! operator unless you have no other choice In this instance, you should check for null
Servator
Servator2y ago
yeah exactly
bialasik__
bialasik__OP2y ago
alr
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