C#Dot Net Perls

 
Visual Studio Encapsulate Field

by Sam Allen

Problem

Quickly and automatically encapsulate fields using Visual Studio 2008's refactoring features. C# requires getters and setters to properly let outside objects access inner fields. But typing all these things out is a big pain. Reduce the number of keystrokes required to code.

Solution

Use the encapsulate field feature in Visual Studio 2008. First I want to introduce the concept and what we want our code to look like in the end. The following samples show some properties in C# 3.0. Note that the value is a special variable that is automatically set. Here is an example of a property in C#.

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

How can I automatically create this code?

By using the Refactor context menu in Visual Studio. Don't worry about the complex name, as the feature is simple to use. Here are the steps you need to take to use this feature. (You should be using C# in Visual Studio 2005 or 2008.)

  1. Go to a private member
    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.)
  2. Right-click on it
    Right-click on string member text. Your context menu will appear. Now, hover your mouse over Refactor -> Encapsulate Field.
  3. Results
    Visual Studio 2008 inserts the property getter and setter for you. The result will look like the following image.
What happens after you use Encapsulate Field.

Use getters in your code

I will show you a brief sample of how you would access the SpecialName getter. This is not the focus of the article, but I will include it for completeness's sake and because at one point I would have liked to see the example. Here's how we would use the property setter shown in the first code block above.

// Use the getter that Visual Studio built for us, just like normal.
SitePage superObject = new SuperObject();
superObject.SpecialString = "Cool";

Note on automatic properties

I want to insert a note here about automatic properties that were introduced in C# 3.0. You can use a more terse syntax for properties. Use the code snippet "prop" to insert a property like this. I don't use this hardly ever, but you can try it using these steps. You must type prop and then press tab twice.

Conclusion

Properties (also called getters and setters) let you control more aspects of your class internals, without dealing with external factors and callers. It is called encapsulation because it is a bit of separation of the inner parts from the outer parts, like a capsule.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge