Back to Devexpress

Encapsulate Property

coderushforroslyn-118645-coding-assistance-code-providers-encapsulate-property.md

latest1.8 KB
Original Source

Encapsulate Property

  • Aug 03, 2020
  • 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.

  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 ):

csharp
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; }
}
vb
Class Program
    Private andrewFuller As Person

    Public Property Age As Integer
        Get
            Return andrewFuller.Age
        End Get
        Set
            andrewFuller.Age = Value
        End Set
    End Property

    Public Property FullName As String
        Get
            Return andrewFuller.FullName
        End Get
        Set
            andrewFuller.FullName = Value
        End Set
    End Property
End Class