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.
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; }
}
}
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.)
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";
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.
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.