BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Refactoring
VS 2005+

Visual Studio Encapsulate Field Command

Sometimes public fields will are in a class to present data. These are accessed in a similar manner to properties but cannot provide validation. Often you will want to upgrade the public fields to properties. Visual Studio provides a command to assist.

Encapsulating a Field

Visual Studio provides some commands to assist with refactoring existing code. In this article we will look at the Encapsulate Field command. This converts a non-private field into a private field, whilst adding a new property that uses the field as its backing store. The new property is given the same visibility as the original field (public, internal, etc.)

To encapsulate a field, start by right-clicking the field name within the code. A context-sensitive menu will be displayed. Select the Refactor submenu and the Encapsulate Field command, as pictured below. The Encapsulate Field dialog box will be displayed. This dialog box allows you to provide a name for the new property, which must be different from that of the existing field.

Visual Studio Encapsulate Field Command

Once a new name has been entered, you are given the option to update any existing references to the field so that they use the property instead. You can also update references to the field within comments or strings if required and you can specify that you would like to preview the changes before accepting them.

Once the changes are accepted, the field will become private and a new property will be created. This property provides get and set accessors, each of which simply reads or updates the private field. You can then add any validation or other code that is required.

Final Notes

When creating a new property, a default name is provided by Visual Studio. If the field has a lower case name, or is prefixed with an underscore, e.g. "_width", the default name will be the existing name with the underscore removed and a capitalised initial letter. When you have a field name such as "Width" and you would like to use this name for the new property, you can use the Rename command to change the field name before encapsulating the field.

Changing a field to a property with the same name is a breaking change, even if the property name matches the original field name. You will need to recompile other code that uses the modified assembly to ensure it continues to operate correctly.

18 January 2009