Why do I get a "possibly null reference" after checking for null?

Charles Burkitt 30 Reputation points
2023-01-24T16:54:42.3833333+00:00

I am checking a property for null, but Visual Studio then warns me about a possibly null reference.
vs question a

vs question b

I am explicitly checking that the DisplayNames property is not null before enumerating it.

Please enlighten me as to what I am doing wrong, if anything.

Thank you.

Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2023-01-24T20:56:46.0133333+00:00

    Probably the analyser is not smart enough in this case. Maybe you can help it:

    var names = vcards[i].DisplayName;
    if( names != null )
    {
       foreach( var displayName in names )
       . . .
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.