2

As topic says. Is it possible to "inject" some null check in source generated setter method? I am using CommunityToolkit.Mvvm 8.1.0.0

For this demo I have simple class Test with private field _someProperty with [ObservableProperty] on top of it.

Source generated setter and getter

public object SomeProperty
{
    get => _someProperty;
    set
    {
        if (!global::System.Collections.Generic.EqualityComparer<object>.Default.Equals(_someProperty, value))
        {
            OnSomePropertyChanging(value);
            OnPropertyChanging(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangingArgs.SomeProperty);
            _someProperty = value;
            OnSomePropertyChanged(value);
            OnPropertyChanged(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedArgs.SomeProperty);
        }
    }
}

My goal: Same, but with null check injected

public object SomeProperty
{
    get => _someProperty;
    set
    {
        if (value is null)
            return;
        if (!global::System.Collections.Generic.EqualityComparer<object>.Default.Equals(_someProperty, value))
        {
            OnSomePropertyChanging(value);
            OnPropertyChanging(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangingArgs.SomeProperty);
            _someProperty = value;
            OnSomePropertyChanged(value);
            OnPropertyChanged(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedArgs.SomeProperty);
        }
    }
}

I just want to check if value is null and omit setting it in setter. In my project I have two DataGrids and TreeView that handles SelectedItem event. They are binding to the same SelectedOobject. This object is initialized in constructor and I don't really want it to be null. This may happen if I refresh DataGrid (cause of filtering) and SelectedOobject may not be "available" in current view and it automatically set to null. I'd rather still use an old object (old reference) than null which becoming annoying to check it in every method.

Julian
  • 5,290
  • 1
  • 17
  • 40
Myszax
  • 33
  • 4
  • What you're asking doesn't seem like an appropriate scenario for Source Generators, it's also not supported in that way, AFAIK. If you want to prevent that `null` is assigned to your reference, you should enable [nullable reference types](https://learn.microsoft.com/dotnet/csharp/nullable-references). – Julian Apr 14 '23 at 11:37

1 Answers1

0

My "workaround" for this case is to create another _tmpSomeProperty with [ObservableProperty] attribute. Bind this property to SelectedItem DataGrid. Then create partial method:

partial void OnTmpSomePropertyChanged(object value)
{
    if (value is null)
        return;
    // do other checks if needed
    SomeProperty = value;
}

With this approach I can control SomeProperty. Is it kinda redundant? I think... But it works as I want.

Myszax
  • 33
  • 4