Skip to content

Add [MemberNotNull] on [ObservableProperty] setter when needed #645

@Sergio0694

Description

@Sergio0694

Overview

Currently, [ObservableProperty] has an issue with nullability annotations. Consider this:

[ObservableProperty]
private string name;

Even if you set Name in the constructor, you'll get a warning saying "name might be null", as the compiler doesn't know that setting Name (to a non null value) also means name is set to a non null value. We can fix this by generating:

public string Name
{
    get => name;

    [MemberNotNull(nameof(name))]
    set => name = value;
}

That is, if:

  • The field is a non nullable reference type
  • Nullable annotations are enabled in the file
  • [MemberNotNull] is available

Then also add [MemberNotNull] in the setter, referring the field.

This way you can set the property in the constructor, and Roslyn will no longer warn that the field might be null and it's not set.

Usage example

The following should not produce a warning:

using CommunityToolkit.Mvvm.ComponentModel;

public partial class MyViewModel : ObservableObject
{
    public MyViewModel()
    {
        Name = "Bob";
    }

    [ObservableProperty]
    private string name;
}

Breaking change?

No

Metadata

Metadata

Assignees

Labels

feature request 📬A request for new changes to improve functionalitymvvm-toolkit 🧰Issues/PRs for the MVVM Toolkit

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions