ReSharper 2020.2 Help

Encapsulate Field refactoring

ReSharper | Refactor | Encapsulate Field…
Control+R E

This refactoring allows you to create an auto-property or a property with the backing field from an existing field. Usages of the field are updated automatically.

In the example below, a field is replaced with an auto-property:

private string myString; public void DoSomething(string input) { myString = input; }
public string MyString { get; private set; } public void DoSomething(string input) { MyString = input; }

Create a new property to expose or replace the field

  1. Place the caret at the declaration or a usage of a field in the editor, or select it in the File Structure window.

  2. Do one of the following:

    • Press Control+R E.

    • Press Control+Shift+R and then choose Encapsulate Field

    • Right-click and choose Refactor | Encapsulate Field in the context menu.

    • Choose ReSharper | Refactor | Encapsulate Field… in the main menu.

    The Encapsulate Field dialog will open.

  3. ReSharper suggests a name for the property based on the field name and the naming style for properties. Modify the name if necessary.

  4. Specify whether to create an auto-property or create a normal property and use the field as its backing field.

  5. By default, ReSharper replaces all (local and external) usages of the field with the property. If you are creating a normal property, you can clear the Do not update local usages checkbox to leave references to the field in the current type.

  6. Specify the property visibility.

  7. If you are creating a normal property, you can tick the Make field private checkbox to disallow direct access to the field.

  8. To apply the refactoring, click Next.

  9. If no conflicts are found, ReSharper performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.

ReSharper. Encapsulate Field refactoring

This feature is supported in the following languages and technologies:

Language: C#Language: VB.NETLanguage: C++Language: HTMLLanguage: ASP.NETLanguage: RazorLanguage: JavaScriptLanguage: TypeScriptLanguage: CSSLanguage: XMLLanguage: XAMLLanguage: ResxLanguage: Build ScriptsLanguage: ProtobufLanguage: JSON
Feature is available in C#Feature is available in Visual Basic .NETFeature is not available in C++Feature is not available in HTMLFeature is not available in ASP.NETFeature is not available in RazorFeature is not available in JavaScriptFeature is available in TypeScriptFeature is not available in CSSFeature is not available in XMLFeature is not available in XAMLFeature is not available in Resource filesFeature is not available in build script filesFeature is not available in ProtobufFeature is not available in JSON

The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see corresponding topics in the ReSharper by Language section.

Last modified: 03 September 2020