0

I am using C# 8 and enable Nullable feature, but I am confused with below scenario enter image description here

it shows errorsList could be null, why is that? btw, if errorsList can be null, why compiler doesn't product a underwave warning for errorsList.Count?

even if I add a null-forgiving operator !, it sill shows errorsList could be null?

enter image description here

  • 1
    Do not post images of code and errors. If you want to show the tooltip I would recommend also including the code as text. Also, intellisense does sometimes give incorrect warnings. Try to restart Visual studio, you may also test [clearing the cache](https://stackoverflow.com/questions/18289936/refreshing-the-auto-complete-intellisense-database-in-visual-studio) – JonasH Sep 29 '22 at 06:30
  • How is `errors` defined? –  Sep 29 '22 at 06:32
  • 1
    [Here are the C# language design notes that show why it behaves like that](https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md) (see the section near the end for `var?`) – Matthew Watson Sep 29 '22 at 08:20

1 Answers1

1

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.

source - see the "Important" section.

So yes, your errorsList is seen as a (nullable) List<Error>? but the compiler does know that it isn't null, so will not complain about using errorsList.Count.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111