C Sharp Programming/Encapsulation2

< C Sharp Programming


Properties encapsulate the control of an object's state.

For example, the following Customer class encapsulates a customer's name:

public class Customer
  // "private" prevents access of _name outside the Customer class:
  private string _name;   

  // The following property allows programmatic changes to _name:
  public string Name
      set { this._name = value; }
      get { return this._name; }

The above Name property has three important parts: the declaration, the set accessor, and the get accessor.

Property declarationEdit

<access modifier> <type> <property name> 
public            string Name

The access modifier determines who can manipulate this data. Properties can be scoped as public, private, protected, or internal.

The type determines what kind of type it can accept or return.

The property name declares the name used to access the property.


Setting the Name property for the Customer class is done through the set accessor, defined using the set keyword.

Similarly, the get keyword creates a get accessor to encapsulate the logic to perform when clients retrieve the value of the property.

Above, the simple set accessor and get accessor make property behave very much like a simple field. That may not be the desired behavior. If not, we can add logic to check the value passed into the set accessor:

public string Name
           set { 
                 if (value != null)
                    this._name = value;
           get {                   
                 if (this._name != null)
                    return this._name;
                    return "John Doe";

Above, if the client requests to set the value to null, the set accessor does not change the field. Also, if the _name field hasn't yet been set, the get accessor returns a default value.

Using propertiesEdit

Clients can use property much like they use simple class fields:

Customer customer = new Customer();

// this will not set the data.
customer.Name = "";

// since the field is not yet set, this will print out: "John Doe"

customer.Name = "Marissa";

The above code prints the following:

John Doe

Accessibility levelsEdit

The various accessibility levels C# provides are, from most public to least:

Accessibility Usage restriction
public None.
internal The containing assembly.
protected internal The containing assembly or types derived from the containing class.
protected The containing class or types derived from it.
private The containing type.

If no accessibility level is specified, a default level is used. They are:

Type Default accessibility
namespace public (and the only allowed)
enum public
class private
interface public
struct private
(others) internal

Note: namespace-level elements (e.g. a class declared directly under a namespace) cannot be declared as stricter than internal.