CS8618 Gives a misleading or confusing message #68716
Labels
Area-Compilers
Concept-Diagnostic Clarity
The issues deals with the ease of understanding of errors and warnings.
help wanted
The issue is "up for grabs" - add a comment if you are interested in working on it
Milestone
Version Used: NET 7
Steps to Reproduce:
string
)This message is either misleading or confusing because while making the property nullability is an easy fix, it is often not the best one. In my experience, adding the
required
modifier is often a better solution. Of course this varies case-by-case.On StackOverflow there are many questions about this. Apparently it confuses people. People propose ugly fixes like:
public string Myproperty { get; set; } = null!;
(Adding the null forgiving operator)or
public string Myproperty { get; set; } = string.Empty;
(The null is replaced with an empty string, which is only slightly better)Also here on GitHub people ask questions about this message, see #37975
My proposal is to change the message to something like: " Non-nullable variable must contain a non-null value when exiting constructor. Consider adding the required modifier or declaring it as nullable."
Adding the
required
modifier also has the advantage that is adds an error if you still forget to initialize, be it in the constructor or with an object initializer.The documentation at
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/nullable-warnings#nonnullable-reference-not-initialized
should be updated as well if this message is adjusted.
Diagnostic Id: CS8618
Expected Behavior:
Non-nullable variable must contain a non-null value when exiting constructor. Consider adding the required modifier or declaring it as nullable.
Actual Behavior:
Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.
The text was updated successfully, but these errors were encountered: