Skip to main content

Introduce Setter Guard Clause

Introduces a value changed check at the start of a property setter, exiting early if the value matches the backing store.

#Availability

Available from the context menu or via shortcuts:

  • when the edit cursor, or caret is on a setter keyword.

Note

This refactoring works only with .NET language constructs.

#Notes

  • This refactoring searches for the first local variable used in the setter. A condition, that compares this variable to the assigned value, is then inserted to the top of the setter body. If this condition is satisfied, a return statement is executed.

#Examples

protected int _PropertyName;
public int PropertyName
{
    get 
    {
        return _PropertyName; 
    }set
    {
        _PropertyName = value;
    }
}
Protected _propertyName As Integer
Public Property PropertyName() As Integer
    Get
        Return _propertyName
    End GetSet(ByVal Value As Integer)
        _propertyName = Value
    End Set
End Property

Result:

protected int _PropertyName;
public int PropertyName
{
    get 
    {
        return _PropertyName; 
    }set
    {
        if (_PropertyName == value)
            return;
        _PropertyName = value;
    }
}
Public Property PropertyName() As Integer
    Get
        Return _propertyName
    End GetSet(ByVal Value As Integer)
        If _propertyName = Value Then
            Return
        End If
        _propertyName = Value
    End Set
End Property

#Screenshot

rsIntroduceSetterGuardClause