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 | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Viorel 125.8K 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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.