Accessing Encapsulate Field

The Encapsulate Field operation enables you to quickly generate properties from a given field. Properties, of course, enable you to protect the field from direct access and to know when the given field is being modified or accessed. To encapsulate a field, you position your cursor over the field and again press Ctrl+. to access the light bulb menu. Figure 9.23 shows an example.

Image

FIGURE 9.23 Encapsulate a field into a property from the Quick Actions menu.

An additional option on the Quick Actions menu for encapsulate field is the choice of the Usages Reference Field. This refers to existing references to the field. Suppose you have a public field. This field might be called both from within the object that defines the field and by other, external objects. You might want to force external callers to use the new property. In this case, you select the Usages Reference Field option.

When you apply the encapsulation, the tool changes your internal field to private (if it was not already private) and then generates a property. The property includes both get and set accessors for the field. If the field was declared as read-only, the encapsulation generates only a get accessor.

Let’s look at the code. Suppose you have the following field declaration.

public int ratingScore;

Suppose you use this field in another assembly, such as this.

Product p = new Product();
p.ratingScore = 3;

Now suppose you want to encapsulate this public field into a public property (with a private backing field). You would do so by highlighting the field in the code editor and pressing Ctrl+. to get started. You would want to select the Usages Reference Field option from the light bulb menu. Figure 9.24 shows the preview available for this refactor. Notice that the code that uses the current field is also being updated to use the new property.

Image

FIGURE 9.24 Preview the encapsulate field changes, including referenced usages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset