The Encapsulate Field refactoring allows you to create a property from an existing field. Usages of the field are updated automatically.
In particular, through the use of properties created with the Encapsulate Field refactoring, you can disallow direct access to that field. The effect achieved with Encapsulate Field is similar to that of the Generate Property code generation feature.
- Place the caret at the name of a field or its usage in the editor, in the File Structure window, in Object Browser or in Class View.
Do one of the following:
- On the main menu, choose ReSharper | Refactor | Encapsulate Field.
- Right-click the type, then click Refactor | Encapsulate Field on the context menu.
- Press Ctrl+Shift+RCtrl+Shift+R, then click Encapsulate Field.
The Encapsulate Field dialog box opens.
Modify a name of a property if necessary in the Property name text box.
By default, ReSharper suggests a property name based on the field name, according to
Code Style Settings for properties.
- Specify what kind of property should be created.
- Select the Replace external usages only check box to leave references to the field from within the current class not encapsulated.
- Specify the property visibility clicking the values in the Property visibility drop-down list.
- Select the Make field private check box to disallow direct access to the field.
- Click Next. If no conflicts are found, ReSharper performs the refactoring immediately. Otherwise, resolve conflicts.
Consider the example below:
After applying the refactoring the myMoveWindowTimer field is encapsulated by the MyMoveWindowTimer property and all its usages are replaced with the usages of the property.