dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Incorrect partial method prototypes for generated observable properties

Open chrisc-onaorg opened this issue 6 months ago • 0 comments

Describe the bug

When decorating a property of a reference or otherwise nullable type with [ObservableProperty] the two-argument partial property-changing and property-changed method prototypes are generated differently than for decorated fields, not considering that the oldValue argument may be null.

Regression

No response

Steps to reproduce

  1. Create a new project targeting .NET 9.0 and depending on CommunityToolkit.Mvvm
  2. Create a class inheriting from ObservableObject
  3. Add the following code to the class:
    [ObservableProperty]
    private object _testA;
    
    [ObservableProperty]
    public object TestB { get; set; }
    
    partial void OnTestAChanged(object? oldValue, object newValue) { /* do nothing */ }
    
    partial void OnTestBChanged(object? oldValue, object newValue) { /* do nothing */ }
    
  4. Note that OnTestBChanged has warning CS8826 on it, because the generated partial declaration is partial void OnTestBChanged(global::System.Object oldValue, global::System.Object newValue); but there's no such warning for OnTestAChanged.

Expected behavior

The On<Property>Changing(oldValue,newValue) and On<Property>Changed(oldValue,newValue) partial method declarations for properties decorated with ObservablePropertyAttribute will be generated the same as for fields decorated with same.

Screenshots

No response

IDE and version

VS 2022

IDE version

17.14.9

Nuget packages

  • [ ] CommunityToolkit.Common
  • [ ] CommunityToolkit.Diagnostics
  • [ ] CommunityToolkit.HighPerformance
  • [x] CommunityToolkit.Mvvm (aka MVVM Toolkit)

Nuget package version(s)

8.4.0

Additional context

The oldValue argument should always be generated as nullable for reference types as the initial call to the methods may be due to setting the property in the constructor (e.g. initial value may be based on a constructor argument, or the change methods may be used to set up and remove event handlers on the property value).

Help us help you

No, just wanted to report this

chrisc-onaorg avatar Jul 23 '25 19:07 chrisc-onaorg