2
votes

Context

C# 8.0 has this features of non-nullable reference types.

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

Question

What reasons are there to not always enable non-nullability in the *.csproj file?

Do you have a checklist? Like, "Don't <Nullable>enable</Nullable> if ... a)... b)... c)..."?

What I can think of

The only reason I can think of is backwards compatibility with existing code. Meaning: turning on the feature and fixing all compiler errors and adjusting code might be just too time-consuming and therefore expensive; perhaps also error-prone.

I've googled but haven't found any other reasons: when not to use non-nullable refernce types in c# - Google Search

Documentation

P.S.

Please let me know if Stack Overflow is the wrong place to ask this question and which other Stack Exchange site would be better suited.

I thought Stack Exchange could be the right placed because of What topics can I ask about here?

  • "a practical, answerable problem that is unique to software development"
1

1 Answers

1
votes

This is because the semantic null checker does not (and can not) cover all conditions to assert that a variable has been assigned from a non-null value, and much many additional marks are needed to help the null checker like the series of attributes, which are even not enough to make everything look ok.

Here is an incomplete list:

  • When a method with return values that depend on the arguments that are complicated and unable to be described by the NotNullWhen series of attribute, it should be marked as nullable, even if it can be asserted not to be null.

  • The null checker can only regard the constructor of a class as the only initialization timing, which means some objects (deserialized entities, virtual actors, razor components, etc.) whose lifetime are owned and managed by a library/framework should be declared with all fields marked as nullable, even if some library defined initializer method (that assigns all the required non-nullable values) is assumed to be called before any other methods.

  • When the flow checker fails to assert the nullable state of a local variable that is inferred to always be nullable with var keyword, or a value that is returned from some code that does not or cannot accurately mark nullability, it is regarded as nullable to enforce a null check or ! before using, even if the programmer clearly knows that is must not be null.

Yes, you can use ! or [AllowNull] series everywhere to disable the null checker, but why not just disabling the whole null checking mechanism then? Therefore the nullable feature would be meaningless.

The nullable reference type feature is only suitable for projects with very basic or trivial logics. As long as it spends more than it helps, it would be reasonable not to enable it.