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.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,646 questions
C#
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.
10,309 questions
{count} votes

Accepted answer
  1. Viorel 112.7K 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