Convert to Property With Change Notification/Introduce Change Notification

Purpose

Introduces change notifications for a property. Use the Code Provider when you need a property to raise an event each time its value changes.

Availability

Available when the caret is on a property, assuming that its parent type implements the INotifyPropertyChanged interface.

Usage

  1. Place the caret on a property declaration.

    Note

    The blinking cursor shows the caret's position at which the Code Provider is available.

    class Person : INotifyPropertyChanged {
        string fullName;
        public string FullName {
            get {
                return fullName;
            }
            set {
                fullName = value;
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. Select Introduce Change Notification from the menu (Convert to Property With Change Notification if the target property is auto-implemented).

After execution, the Code Provider adds an event invocation statement to the property setter. The Property Changed event is invoked with an event-rising method if the parent type contains such a method. Otherwise, the Code Provider uses the boilerplate event invocation statement.

The Introduce Setter Guard Clause is automatically called for the target property's setter to prevent the unwanted event invocation in case the new value equals the old one.

class Person : INotifyPropertyChanged {
    string fullName;
    public string FullName {
        get {
            return fullName;
        }
        set {
            if (fullName == value)
                return;
            fullName = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FullName)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}