Skip to main content

Encapsulate Property

  • 2 minutes to read

Purpose

Wraps a selected object’s properties in new properties declared in the active type. This Refactoring is helpful when you need to expose a protected or private object’s properties that are declared as a current type’s field.

Availability

Available when the cursor is in a field whose type exposes one or more public properties.

Usage

  1. Place the caret in a field.

    Note

    The blinking cursor shows the caret’s position at which the Refactoring is available.

    class Program {
        private Person andrewFuller;
    }
    
    public class Person {
        public int Age { get; set; }
        public string FullName { get; set; }
        protected string PhoneNumber { get; set; }
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select the Encapsulate Property from the menu.
  4. Select the properties to encapsulate using the mouse or Space key.
  5. Hit Enter to confirm the selection.

After execution, the Refactoring adds properties to the active type. The added properties give access to the selected field’s properties. After adding properties, this refactoring updates all references so that they use the newly generated properties.

The following code is generated in the Program class if you selected all the available properties (Age and FullName):

class Program {
    private Person andrewFuller;

    public int Age { get => andrewFuller.Age; set => andrewFuller.Age = value; }
    public string FullName { get => andrewFuller.FullName; set => andrewFuller.FullName = value; }
}