coderushforroslyn-118442-coding-assistance-code-providers-convert-to-property-with-change-notification-introduce-change-notification.md
Introduces change notifications for a property. Use the Code Provider when you need a property to raise an event each time its value changes.
Available when the caret is on a property, assuming that its parent type implements the INotifyPropertyChanged interface.
Place the caret on a property declaration.
Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
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;
}
Class Person
Implements INotifyPropertyChanged
Private _fullName As String
Public Property FullName() As String
Get
Return _fullName
End Get
Set(value As String)
If _fullName Is Value Then
Return
End If
_fullName = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(FullName)))
End Set
End Property
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
End Class