Search code examples
c#nullable-reference-typesmvvm-toolkit

How to handle ViewModel-Properties with nullables enabled


When using an MVVM framework like the MVVM Community Toolkit you usually have a call to SetProperty or a similar method in a property setter that automatically invokes the PropertyChanged event and sets the corresponding field.

private string _str;
public string Str { get => _str; set => SetProperty(ref _str, value); }

public Foo(string str) { Str = str; }

However, when using nullables, I get a warning that the non-nullable field _str must contain a non-null value, even though I have set the field via the property.

Is there a solution to this problem besides writing private string _str = null!; or using the MemberNotNull attribute, because that's a lot of boilerplate in my opinion.


Solution

  • Non-nullable fields should have a value from beginning existence of the object and should not be null at any point of time. So do not assign null to such fields.

    In case of strings you can an empty string:

    private string _str = String.Empty;
    

    or you can promise to the compiler that calling a setter will set the field:

    public class Foo : ObservableObject
    {
        private string _str;
    
        public string Str
        {
            get => _str;
    
            [MemberNotNull(nameof(_str))]
            set => SetProperty(ref _str, value);
        }
    
        public Foo(string str)
        {
            Str = str;
        }
    }
    

    but the best and the most efficient you can do is to just set the field in the constructor:

    public class Foo : ObservableObject
    {
        private string _str;
    
        public string Str
        {
            get => _str;
            set => SetProperty(ref _str, value);
        }
    
        public Foo(string str)
        {
            _str = str;
        }
    }
    

    During construction no one had a chance to attach to the PropertyChanged event, so there's no reason to call SetProperty(...).