Udostępnij za pośrednictwem


Encapsulate Field

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 public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, 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 private, 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 Encapsulate Field Dialog Box.

Remarks

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 and 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 feature. Code Snippets are modifiable. For more information, see How to: Manage Code Snippets.

For more information about when to use fields and when to use properties, see Property Procedures vs. Fields.

See Also

Tasks

How to: Refactor Code with Encapsulate Field

Concepts

Refactoring

Code Snippets (C#)