ReSharper Web Help

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.

To encapsulate a field
  1. 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.
  2. 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+R, then click Encapsulate Field.
  3. 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.

  4. Specify what kind of property should be created.
  5. Select the Replace external usages only check box to leave references to the field from within the current class not encapsulated.
  6. Specify the property visibility clicking the values in the Property visibility drop-down list.
  7. Select the Make field private check box to disallow direct access to the field.
  8. 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 filed is encapsulated by the MyMoveWindowTimer property and all its usages are replaced with the usages of the property.

See Also

Procedures