Search code examples
c#nullable-reference-types

How to avoid compiler errors that private fields populated during construction "may be null"


A very simple example but often you have private class fields or properties set during construction, and want to pull this out into helper methods:

class MyClass
{
 private List<int> _list;

 public MyClass()
 {
  PopulateList();
 }

 private void PopulateList()
 {
  _list = new(){1,2,3};
 }
}

Because _list is populated in a separate method rather than in the constructor, the compiler gives a warning "CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable."

This is correct, but as developer I know the field will not be null. I don't want to make it nullable to appease the compiler, or disable NRTs and null-checking generally, and I don't want to move the contents of PopulateList into the ctor as it gets messy.

Other than disable the warning (#pragma warning disable CS8618) does C# provide any way to inform the compiler "it's OK"? Or do we simply have to work around this limitation in the compiler's ability to check for null?


Solution

  •     [MemberNotNull(nameof(_list))]
        private void PopulateList()
        {
            _list = new() { 1, 2, 3 };
        }