5.7. 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, if the caller wants to alter the state of an object, the user does so indirectly using accessor (i.e., "getter") and mutator (i.e., "setter") methods. In C#, encapsulation is enforced at the syntactic level using the public, private, internal, and protected keywords. 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 ...

Get Pro C# 2010 and the .NET 4 Platform, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.