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 section.

    For more information, see Creating Console Applications (Visual C#).

  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. On the Refactor menu, click Encapsulate Field.

    The Encapsulate Field Dialog Box appears.

    You can also type the keyboard shortcut CTRL+R, E to display the Encapsulate Field dialog box.

    You can also right-click the cursor, point to Refactor, 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 Program with the following code. For more information, see Creating Console Applications (Visual C#).

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

Concepts

Refactoring

Reference

Encapsulate Field