Search code examples
c#.net-corewarningsnon-nullable

Avoiding null reference warnings when working with property and member


I have a class with the following member and property:

private SomeFormModel _someModel;

[MemberNotNull(nameof(_someModel))]
public SomeFormModel SomeModel
{
    get => _someModel;
    set
    {
        _someModel = value;
        _someModel.Subview = true;
    }
}

public CurrentFormModel()
{
    SomeModel = new();
}

The getter of SomeModel raises the following warnings:

    CS8774  Member '_someModel' must have a non-null value when exiting.
    CS8603  Possible null reference return.

If I remove the MemberNotNull attribute, CurrentFormModel constructor raises a warning:

    CS8618  Non-nullable field '_someModel' must contain a non-null value when exiting constructor...

What is the proper way to avoid the warnings?


Solution

  • The MemberNotNullAttribute should be applied to only the setter of the property:

    public SomeFormModel SomeModel
    {
        get => _someModel;
        [MemberNotNull(nameof(_someModel))]
        set
        {
            _someModel = value;
            _someModel.Subview = true;
        }
    }
    

    Applying it to the property itself is the same as applying it to both the getter and setter. Clearly, the getter does not guarantee that _someModel is not null after it returns. It is the setter that does.