I am using C# 8 and enable Nullable feature, but I am confused with below scenario
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?
CodePudding user response:
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
.