How to: Refactor Code with Encapsulate Field
Collapse the table of content
Expand the table of content
This documentation is archived and is not being maintained.

How to: Refactor Code with Encapsulate Field 

The following procedure describes how to create a property from an existing field, and then update your code with references to the new property. Use this procedure to perform the Encapsulate Field refactoring operation.

To create a property from a field

  1. Create a console application as described in the example below.

    For more information, see Console Application Template.

  2. In the Code and Text Editor, place the cursor in the declaration, on the name of the field that you want to encapsulate. In the example below, place the cursor on the word width:

       public int width, height;
    
  3. Select Encapsulate Field from the Refactor menu. The Encapsulate Field Dialog Box appears.

    You can also type the keyboard shortcut CTRL+R, CTRL+F to display the Encapsulate Field Dialog Box.

    You can also right-click the cursor, point to Refactor on the context menu, and then click Encapsulate Field to display the Encapsulate Field Dialog Box.

  4. Specify settings.

  5. Press ENTER, or click the OK button.

  6. If you selected the Preview reference changes option, then the Preview Reference Changes window opens. Click the Apply button.

    The following get and set accessor code is displayed in your source file:

            public int Width
            {
                get
                {
                    return width;
                }
    
                set
                {
                    width = value;
                }
            }
    

    The code in the Main method is also updated to the new Width property name.

    Square mySquare = new Square();
    mySquare.Width = 110;
    mySquare.height = 150;
    // Output values for width and height.
    Console.WriteLine("width = {0}", mySquare.Width);
    
    

Example

To set up this example, create a console application named EncapsulateFieldExample, and then replace Class1 with the following code. For more information, see Console Application.

class Square
{
    // Select the word 'width' then use Encapsulate Field.
    public int width, height;
}
class MainClass
{
    public static void Main()
    {
        Square mySquare = new Square();
        mySquare.width = 110;
        mySquare.height = 150;
        // Output values for width and height.
        Console.WriteLine("width = {0}", mySquare.width);
        Console.WriteLine("height = {0}", mySquare.height);
    }
}

See Also

Show:
© 2016 Microsoft