CHAPTER 5 UNDERSTANDING ENCAPSULATION
In these cases, it can become rather verbose to define private backing fields and simple property
definitions multiple times. By way of an example, if you are modeling a class that requires 15 private
points of field data, you end up authoring 15 related properties that are little more than thin wrappers
for encapsulation services.
To streamline the process of providing simple encapsulation of field data, you may use automatic
property syntax. As the name implies, this feature will offload the work of defining a private backing field
and the related C# property member to the compiler using a new bit of syntax. To illustrate, create a new
Console Application named AutoProps. Now , consider the reworking of the Car class, which uses this
syntax to quickly create three properties:
class Car
{
// Automatic properties!
public string PetName { get; set; }
public int Speed { get; set; }
public string Color { get; set; }
}
Note Visual Studio provides the prop code snippet. If you type “prop” and press the Tab key twice, the IDE will
generate starter code for a new automatic property! You can then use the Tab key to cycle through each part of
the definition to fill in the details. Give it a try!
When defining automatic properties, you simply specify the access modifier, underlying data type,
property name, and empty get/set scopes. At compile time, your type will be provided with an
autogenerated private backing field and a fitting implementation of the get/set logic.
Note The name of the autogenerated private backing field is not visible within your C# code base. The only way
to see it is to make use of a tool such as ildasm.exe.
Unlike traditional C# properties, however, it is not possible to build read-only or write-only
automatic properties. While you might think you can just omit the get; or set; within your property
declaration as follows:
// Read-only property? Error!
public int MyReadOnlyProp { get; }
// Write only property? Error!
public int MyWriteOnlyProp { set; }
this will result in a compiler error. When you are defining an automatic property, it must support both
read and write functionality. Recall the following:
// Automatic properties must be read and write.
public string PetName { get; set; }
200