dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Allow custom property attributes for [ObservableProperty]

Open Sergio0694 opened this issue 1 year ago • 4 comments

Overview

Right now, it's not possible to specify property attributes when using [ObservableProperty], which has been a pain point for some users, as it forces you to go back to manual properties in that case. There's been several asks for this in the past, see (#228, #217, #208). We could technically support this via the explicit property: target, which Roslyn ignores but doesn't block. That is:

[ObservableProperty]
[property: JsonPropertyName("name")]
private string? name;

The generator would emit:

[JsonPropertyName("name")]
public string? Name
{
    get => name;
    set => ...
}

This would effectively allow users to have perfect control over attributes on target properties.

Note: Roslyn will currently emit a diagnostic in this case, ~~so users would have to suppress it or just ignore it. Just not the perfect tooling experience, but it would still solve the issue and be a valid solution for now with no language changes needed.~~ which we can automatically suppress with a dedicated diagnostic suppressor, so not a problem.

Sergio0694 avatar Aug 31 '22 13:08 Sergio0694

@333fred I know you were doing some work to block uses of invalid attribute targets, was that restricted to not recognized targets (ie. CS0658), or would that include invalid targets (ie. CS0657) too? As in, could we rely on that not being an error?

Sergio0694 avatar Aug 31 '22 13:08 Sergio0694

Additionally (cc. @chsienki) would there be a way for a generator to suppress CS0657 on that field on behalf of users? As in, a way for it to basically tell Roslyn that yes those are ignored, but the generator actually needs that info, so it shouldn't be a warning. Being able to suppress those CS0657 from the generator would make the UX much better for the end users 🙂

Sergio0694 avatar Aug 31 '22 13:08 Sergio0694

@Sergio0694 The generator can't do that, but you can ship a diagnostic suppressor in the same assembly. They were basically invented for this purpose :) https://github.com/dotnet/roslyn/blob/32c1f2d2df534f9ae3679807ecdfdd0706e8da6d/docs/analyzers/DiagnosticSuppressorDesign.md

chsienki avatar Aug 31 '22 18:08 chsienki

Ooh that's awesome, thank you! I'll look into it, this seems very promising then 😄

Sergio0694 avatar Aug 31 '22 18:08 Sergio0694