"Non-nullable field 'X' is uninitialized" Warning.

Hi, I recently started to use the Nullable types feature, it seems to give a false warning for the following scenario: 

Mind that my class contains a string with a backing field, this warning does not appear when using auto-property.

Is this behavior intentional?
I think the compiler should be smart enough to understand that `myString` will be initialized as there is no condition in the setter before line 16.

Using Rider 2022.1

1 comment
Comment actions Permalink

Hi Nimrod m, thank you for your question.

This warning comes from the compiler, that's why Rider shows it. Showing this warning is useful when "warnings as errors" is enabled. Otherwise, the project will not compile, and there will be no explanation in the editor.

In addition, the compiler does not know what code is written in the MyString setter.

You can workaround the problem by annotating the setter to let the compiler know that the setter should initialize the field. The compiler uses this information in the constructor to know that the field has been initialized and, when parsing the setter, checks that the annotation is correct.

#nullable enable
        public class MyClass
        private string myString;

        public MyClass()
            myString = "";

        public MyClass(string myString)
            MyString = myString;

        public string MyString
            get => myString;
                myString = value;



Please sign in to leave a comment.