Visual Studio Encapsulate Field

by Sam Allen - Updated January 7, 2010

You need to make properties and want to use the Encapsulate Field feature in Visual Studio 2008. The C# language has getters and setters for accessing inner fields. Reduce the number of keystrokes required for good code design and style. Here we see how you can refactor fields in your C# code using Visual Studio 2008.

Encapsulate field result

Refactoring in Visual Studio

Here we use the Encapsulate Field feature in Visual Studio 2008. This will allow you to turn fields into property getters and setters very quickly. The following example shows properties in the C# language version 3.0. Note that value is a special variable that is automatically set.

class SitePage
{
    string _specialString;
    public string SpecialString
    {
        get { return _specialString; }
        set { _specialString = value; }
    }
}

Making properties automatically

We can use the Refactor menu in Visual Studio by following these steps. They apply to your C# code in Visual Studio 2005 or 2008. First, in the code editor, make a simple class or open one up in a project. Create or go to a private string member. Members are private by default.

Next steps. Right-click your mouse on the string member name. Your context menu will appear. Hover your mouse over Refactor -> Encapsulate Field. Visual Studio 2008 inserts the property getter and setter for you. The result will look like the example on this document.

Using getters in your code

Here we access the SpecialString getter shown in the above example. The property can be used like any other member field or method in your C# code. There is usually no performance penalty with property usage.

(See Property Test.)

SitePage superObject = new SuperObject();
superObject.SpecialString = "Cool";

Using automatic properties. Automatic properties—also called automatically implemented properties—were introduced in the C# language version 3.0 and use shorter syntax for properties. Use the code snippet "prop" to insert a property like this. Try typing prop and then pressing tab twice.

Summary

Here we looked at how you can use the Encapsulate Field menu item in Visual Studio. Properties let you control more aspects of your class internals, without changing outside code. Encapsulating code means separating of the inner parts from the outer parts, like a capsule. This article used source code in the C# language.

(Do not copy this page.)

Dot Net Perls | Search
Visual Studio | Settings.settings in Visual Studio | Visual Studio Debugging Tutorial | Visual Studio Post-Build, Pre-Build Macros | Visual Studio Tab Options | Visual Studio TODO Comments
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen