TheDeveloperBlog.com


C# Encapsulate Field

Encapsulate field. Properties are used often in C# programs. They can be made with the Encapsulate Field feature in Visual Studio. The C# language has getters and setters for accessing inner fields. It is possible to reduce the number of keystrokes required.


Example. Here we use the Encapsulate Field feature in Visual Studio. 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: Value is a special variable that is automatically set. It is a contextual keyword.

Value
Example that shows property: C#

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


Encapsulate field. We can use the Refactor menu in Visual Studio by following these steps. They apply to your C# code in Visual Studio. First, in the code editor, make a simple class or open one up in a project.

Then: Create or go to a private string member field. Members are private by default.

Next: Right-click your mouse on the string member name. Your context menu will appear. Hover your mouse over Refactor > Encapsulate Field.

Finally: Visual Studio inserts the property getter and setter. The result will look like the example on this document.


Property example. 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.

Property
Example that shows property usage: C#

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

Automatic properties (automatically implemented properties) were introduced in the C# language version 3.0. They use shorter syntax for properties. Use the code snippet—try typing "prop" and then pressing tab twice.

Snippets

Summary. We used the Encapsulate Field menu item in Visual Studio. Properties let you control more aspects of your class internals, without changing outside code. Encapsulating code separates the inner parts from the outer parts, like a capsule.