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
Overview
Currently,
[ObservableProperty]has an issue with nullability annotations. Consider this:Even if you set
Namein the constructor, you'll get a warning saying "name might be null", as the compiler doesn't know that settingName(to a non null value) also meansnameis set to a non null value. We can fix this by generating:That is, if:
[MemberNotNull]is availableThen 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:
Breaking change?
No