CHAPTER 5 UNDERSTANDING ENCAPSULATION
example, here is a private enumeration (named CarColor) nested within a public class (named
SportsCar):
public class SportsCar
{
// OK! Nested types can be marked private.
private enum CarColor
{
Red, Green, Blue
}
}
Here, it is permissible to apply the private access modifier on the nested type. However, nonnested
types (such as the SportsCar) can only be defined with the public or internal modifiers. Therefore, the
following class definition is illegal:
// Error! Nonnested types cannot be marked private!
private class SportsCar
{}
The First Pillar: C#’s Encapsulation Services
The concept of encapsulation revolves around the notion that an object’s internal data should not be
directly accessible from an object instance. Rather, class data is defined as private. If the caller wants to
alter the state of an object, the user does so indirectly using public members. To illustrate the need for
encapsulation services, assume you have created the following class definition:
// A class with a single public field.
class Book
{
public int numberOfPages;
}
The problem with public data is that the data itself has no ability to “understand” whether the
current value to which they are assigned is valid with regard to the current business rules of the system.
As you know, the upper range of a C# int is quite large (2,147,483,647). Therefore, the compiler allows
the following assignment:
// Humm. That is one heck of a mini-novel!
static void Main(string[] args)
{
Book miniNovel = new Book();
miniNovel.numberOfPages = 30000000;
}
Although you have not overflowed the boundaries of an int data type, it should be clear that a mininovel with a page count of 30,000,000 pages is a bit unreasonable. As you can see, public fields do not
provide a way to trap logical upper (or lower) limits. If your current system has a business rule that states
a book must be between 1 and 1,000 pages, you are at a loss to enforce this programmatically. Because of
this, public fields typically have no place in a production-level class definition.
190