Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading