ReSharper Web Help

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 Generate Property  code generation feature.

To encapsulate a field
  1. Position the caret on the field (any usage or declaration) in the editor.
  2. On the ReSharper menu or context menu, choose Refactor | Encapsulate Field.
  3. In the dialog box that opens, select the necessary options and click Continue.

Example

  • Consider the following piece of code:
    Encapsulate Field refactoring
  • With the caret on the field myBankAccountTotal, invoke the Encapsulate Field refactoring. The following dialog box is displayed:
    Encapsulate Field refactoring
  • 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 Settings  for 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.
  • After you click Continue, the code is updated as shown below:
    Encapsulate Field refactoring

See Also

Procedures