The Encapsulate Field refactoring operation enables you to quickly create a property from an existing field, and then seamlessly update your code with references to the new property.
When a field is, other objects have direct access to that field and can modify it, undetected by the object owning that field. By encapsulating that field through the use of , you can disallow direct access to fields.
To create the new property, the Encapsulate Field operation changes the access modifier for the field that you want to encapsulate to, and then generates get and set accessors for that field. In some cases, only a get accessor is generated, such as when the field is declared read-only.
The refactoring engine updates your code with references to the new property in the areas specified in the Update References section of the.
The Encapsulate Field operation is only possible when the cursor is positioned on the same line as the field declaration.
For declarations that declare multiple fields, Encapsulate Field uses the comma as a boundary between fields, and initiates refactoring on the field that is nearest the cursor, on the same line as the cursor. You can also specify which field you want to encapsulate by selecting the name of that field in the declaration.
The code that is generated by this refactoring operation is modeled by the Encapsulate Field Code Snippets. Code Snippets are modifiable. For more information, see.
For more information on when to use fields and when to use properties, see.