Search code examples
c#null-check

What is the correct way to check for "possibly null" references?


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#)


Solution

  • 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