Skip to content

Create PropertyChangedEventArgs statically #42

@ElemarJR

Description

@ElemarJR

Implement a C# version of @ljw1004 Analyzer/CodeFix

As he describes it:

When you implement INotifyPropertyChanged, if one of your properties changes,
you are expected to fire off a PropertyChanged event. This takes a
PropertyChangedEventArgs argument. People sometimes construct a New
instance of the PropertyChangedEventArgs class every single time the
property changes. This amounts of a lot of heap allocations, which
hurt performance in XAML apps.

This analyzer looks for every place where you construct an instance of PropertyChangedEventArgs
in something other than a static field. Its fix Is to instead construct the instance
in a static field.

NOTE: This analyzer doesn't do work to avoid name-clashes. If the static field already
exists, it will give poor results.

Sample Video in https://pbs.twimg.com/tweet_video/B2tTZRNCIAAHlqx.mp4

Reference implementation (VB) in

https://github.com/ljw1004/dotnet-code-analyzer/blob/master/dotnet-code-analyzer/Analyzer_XamlAppTips/UseStaticChangedCS.vb

This is essentially a refactoring, so we are classifying it as a Hidden diagnostic.
Diagnostic Id: CC0106

This:

private string name;
public string Name
{
    get
    {
        return name;
    }

    set
    {
        name = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name));
    }
}

Becomes:

private string name;
public string Name
{
    get
    {
        return name;
    }

    set
    {
        name = value;
        PropertyChanged?.Invoke(this, nameChanged);
    }
}
private static PropertyChangedEventArgs nameChanged = new PropertyChangedEventArgs(nameof(Name);

If there is already a field named nameChanged, add 1 to it, if there is already on with 1, add 2, and so on.

Diagnostic Id; CC0106

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions