Encapsulate Field refactoring
Refactor | Encapsulate Field…
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:
Before refactoring
private string myString;public void DoSomething(string input){ myString = input;}
After refactoring
public string MyString { get; private set; }public void DoSomething(string input){ MyString = input;}
tip
You can also generate properties for several fields in the class using the Generate Properties command.
Place the caret at the declaration or a usage of a field in the editor, or select it in the Structure window window.
Do one of the following:
Press CtrlShift0R and then choose Encapsulate Field.
Choose Refactor | Encapsulate Field from the main menu.
The Encapsulate Field dialog will open.
JetBrains Rider suggests a name for the property based on the field name and the naming style for properties. Modify the name if necessary.
Specify visibility for the created property.
If you choose to create an auto-property, the field will be removed and its usages replaced with the property everywhere.
Otherwise, the field will be used as the backing field for the new property and you will be able to choose how to update the property and its usages:
Select Read usages/Write usages to replace the corresponding usages of the filed with the property.
Select Name usages to replace occurrences of the field name inside
nameof()
expressions and XML documentation comments with the name of the property.Select Do not update local usages to leave references to the field in the current type.
If the field was not private, select Make field private to disallow direct access to the field outside the current type.
To apply the refactoring, click Next.
If no conflicts are found, JetBrains Rider performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
tip
Right after the refactoring has been completed, all changes that it makes anywhere, including other files, are registered as a single operation. So you can use the Undo action Ctrl0Z to roll back all these changes with a single keystroke.
tip
You can also invoke this refactoring from the acton list - just press AltEnter when your caret is on a field and choose Encapsulate Field.
