The Encapsulate Field refactoring allows you to quickly 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
- Position the caret on the field (any usage or declaration) in the editor.
- On the ReSharper menu or context menu, choose Refactor | Encapsulate Field.
- In the dialog box that opens, select the necessary options and click Continue.
- Consider the following piece of code:
- With the caret on the field
myBankAccountTotal, invoke the Encapsulate Field refactoring. The following dialog box is displayed:
- Do the following to apply the refactoring successfully:
- 3.a. Type the new property name in the Property name field. By default, ReSharper suggests a property name
based on the field name, according to
Code Style Settingsfor properties.
- 3.b. Select an option in the Property kind section to specify whether or not the new property should have both a getter and a setter, or whether it should be implemented as an auto-property.
- 3.c. Select Replace external usages only to leave references to the field from within the current class not encapsulated.
- 3.d. Select a visibility level in the Property visibility drop-down list.
- 3.e. Select Make field private to disallow direct access to the field.
- 3.a. Type the new property name in the Property name field. By default, ReSharper suggests a property name based on the field name, according to
- After you click Continue, the code is updated as shown below: