dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

ObservablePropertyAttribute on a field: avoid CS0169?

Open chucker opened this issue 3 years ago • 5 comments

I made a simple INPC property like so:

[ObservableProperty]
private bool _IsReadOnly;

As expected, I can now bind to IsReadOnly in XAML. Great! However, VS now shows me a warning:

Severity    Code    Description Project File    Line    Category    Suppression State
Warning CS0169  The field 'MyViewModel._IsReadOnly' is never used MyProject   MyViewModel.cs  148 Build   Active

Makes sense; it doesn't understand that the field exists only for the generated code. However:

  1. is that the expected behavior?
  2. even if I wrap the field in #warning pragma disable CS0169, the warning doesn't go away. Am I missing something?

chucker avatar Aug 10 '22 14:08 chucker

(Hm, maybe https://github.com/CommunityToolkit/dotnet is the more appropriate repo? Not sure.)

chucker avatar Aug 10 '22 14:08 chucker

Mmh is your code actually compiling? That field name is incorrect, as it starts with an uppercase character 🤔

Sergio0694 avatar Aug 10 '22 16:08 Sergio0694

Mmh is your code actually compiling? That field name is incorrect, as it starts with an uppercase character 🤔

I tried with the variants isReadyOnly and _isReadOnly as well. In all three cases, the generated code looks correct; both its set and get point to my field.

So I don't think that's the issue.

However, my use of the .NET 5 SDK (due to some regressions in 6.0) could be it?

{
	"sdk": {
		"version": "5.0.400"
	}
}

chucker avatar Aug 10 '22 16:08 chucker

@chucker which version of the MVVM package are you using? If it's 8.0, I'm pretty sure you have to be building with .NET 6.

michael-hawker avatar Aug 10 '22 18:08 michael-hawker

It is indeed 8.0. Other than the compiler warning, it seems to work fine (at least for [ObservableProperty]).

If someone can confirm that this is indeed a known issue in the .NET 5 SDK, then fair enough.

chucker avatar Aug 15 '22 08:08 chucker

Couldn't repro this, but I've added one more unit test to cover this too in a PR. Thank you! 🙂

Sergio0694 avatar Jan 01 '23 17:01 Sergio0694