Encapsulate Field (read-only)

Encapsulates a field into a read-only property and replaces all occurrences of this field throughout the class with the newly declared property.

Purpose

Accessing data directly (through fields) may lead to a separation of the algorithms that process the data from their actual storage. Data encapsulation (data storage and processing in one place) makes code management easier than the alternatve, where data changing and validation routines can appear in multiple different places throughout the code. So, if you have a field that requires additional processing while accessing data, the Encapsulate Field (read-only) refactoring will provide the first step in better organization of your data access interface.

Availability

Available from the context menu or via shortcuts:

  • This refactoring is available for .NET property declarations only, and won't work with native C++ constructs.
  • when the edit cursor or caret is on a field declaration.
  • when the name is selected within the field declaration statement.

If the selected field is already used to store a property's value, then Encapsulate Field (read-only) will be unavailable.

Notes

  • You can choose the newly declared property's location using the target picker (see Settings below).

Options

  • You can control whether the newly declared property should be located at the top of the type, right below the source field or at the location you choose with the target picker.
  • You can specify if current references to the encapsulated field should be replaced with the newly declared property. Three options are available: no replacement, automatic replacement for all field references and Replacer Progress Indicator utilization.
  • You can specify how to change visibility of the field and the newly declared property.

Example

public string TestString;
public string AddString(string SrcString)
{
    return String.Format("{0}{1}", SrcString, TestString);
}
Public TestString As String
Public Function AddString(ByRef SrcString As String) As String
    Return String.Format("{0}{1}", SrcString, TestString)
End Function

Result:

private string TestString;
public string AddString(string SrcString)
{
    return String.Format("{0}{1}", SrcString, TestString1);
}
public string TestString1
{
    get
    {
        return TestString;
    }
}
Private TestString As String
Public Function AddString(ByRef SrcString As String) As String
    Return String.Format("{0}{1}", SrcString, TestString1)
End Function
Public Property TestString1() As String
    Get
        Return TestString
    End Get
End Property

Animation

CSharpEncapsulateFieldRO