I have this bit of relevant code:
if (boardMap[i,j] != null) {
Console.Write(boardMap[i,j].color.ToString() " " boardMap[i,j].type.ToString());
}
else {
Console.Write("X");
}
boardMap
contains potentially null values, which is why I implemented the if
statement checking if the boardMap[i,j]
item is null. However, I get a warning in line 2 telling me that boardMap[i,j]
is possibly null.
How do I fix this -> What is the correct way to do null checks like this?
(Please note, I am very much a beginner with dotnet and C#)
CodePudding user response:
Currently compiler does not handle this case very well (and arrays in general). To help compiler determine the null-state of the item you can use pattern matching with empty property pattern:
if (boardMap[i,j] is {} map)
{
Console.Write(map.color.ToString() " " map.type.ToString());
}
else
{
Console.Write("X");
}
or introduce a variable:
var map = boardMap[i,j];
if (map != null)
{
...
}
CodePudding user response:
As of C# 8.0 and later, you can use the null-forgiving operator. Just append ! after whatever might be null. It basically tells the compiler that it should turn off possibly null warnings for this occurrence.
if (boardMap[i,j] != null) {
Console.Write(boardMap[i,j]!.color.ToString() " " boardMap[i,j]!.type.ToString());
}
else {
Console.Write("X");
}
CodePudding user response:
Despite your if
, the compiler is not able to infer that boardMap[i,j]
won't be null, so it issues this warning.
EDIT @GuruStron points out that this kind of warning is only issued since C#8. I was not able to find the reference for this, but I'm inclined to believe it. Which implies that if one has this problem, he is using at least C#8.
You can deal generally with this kind of issues in different ways, depending on your needs.
Use attributes to signal the compiler that the variable won't be null. See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis and also this question: How to suppress Possible Null Reference warnings
Use nullable reference types. See https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references
Change the code so the compiler will not issue a warning, using
!
, or?
and??
operators or the other answers suggestions.Ignore the compiler warning, because you know better.
CodePudding user response:
In a multithreaded app boardMap[i,j]
could potentially be set to null 10 nanoseconds after you've checked it not to be null. That's (probably) why the compiler now complains.
Of course it depends on your code.
If you're sure that array is only handled by one thread, your null check is safe as is and you can just ignore the warning here.
An easy way to protect you code in a multithreaded scenario (without locking) is to assign the array value to a local variable. And do the null check and the Console.Write
on that variable. Then the null check is safe. See post by @GuruStron