Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Sergio0694 opened this issue Mar 14, 2023 · 0 comments · Fixed by #646
Closed

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

Sergio0694 opened this issue Mar 14, 2023 · 0 comments · Fixed by #646
Assignees
Labels
feature request 📬 A request for new changes to improve functionality mvvm-toolkit 🧰 Issues/PRs for the MVVM Toolkit

Comments

@Sergio0694
Copy link
Member

Sergio0694 commented Mar 14, 2023

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

@Sergio0694 Sergio0694 added feature request 📬 A request for new changes to improve functionality mvvm-toolkit 🧰 Issues/PRs for the MVVM Toolkit labels Mar 14, 2023
@Sergio0694 Sergio0694 self-assigned this Mar 14, 2023
@Sergio0694 Sergio0694 added this to 8.2 Mar 14, 2023
@Sergio0694 Sergio0694 moved this to 📋 Backlog in 8.2 Mar 14, 2023
@github-project-automation github-project-automation bot moved this from 📋 Backlog to ✅ Done in 8.2 Mar 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request 📬 A request for new changes to improve functionality mvvm-toolkit 🧰 Issues/PRs for the MVVM Toolkit
Projects
No open projects
Status: Done
Development

Successfully merging a pull request may close this issue.

1 participant