The Encapsulate Field refactoring allows you to quickly create a property from an existing field. Usages of the field are automatically updated in the process.
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.
To encapsulate a field:
-
Position the caret on the field (any usage or declaration) in the editor.
-
Do one of the following:
- Select ReSharper | Refactor | Encapsulate Type in the main menu.
- Right-click on the name of the field in the editor and select Refactor | Encapsulate Type in the context menu.
- Press Ctrl + Shift + R and select Encapsulate Type.
- In the dialog that appears, select the necessary options and click Continue.
Example
- Consider the following piece of code:

- With the caret on the field
myBankAccountTotal , invoke the Encapsulate Field refactoring. The following dialog is displayed:

- Do the following to apply the refactoring successfully:
- Type the new property name. By default, ReSharper suggests a property name based on the field name, according to the Code Style Settings for properties.
- Select which accesses will be encapsulated using the Encapsulate reads and Encapsulate writes checkboxes. At least one of the two must be selected to use the refactoring. Also, if a property already exists for this field, the corresponding checkbox will not be available.
- Select Make field private if you want to disallow direct access to the field.
- Select whether all references in the solution will be encapsulated (All ) or just those outside the class (External).
- Select the appropriate Property visibility. This will define the ultimate visibility of the original field.
- If you select Keep modified files open, ReSharper will open any modified files in new editor tabs, and then you will need to save the changes yourself. Clear this check box if you want ReSharper to save the changes automatically, without opening the files.
- After you click Continue, the code is updated as shown below:

See Also
Refactoring Code