Encapsulation and Class Development

Of all the OO concepts, encapsulation is the easiest.   The idea is to take data and behaviors and wrap them
into one logical and physical entity.  The details of the implementation are hidden from the user of the object.
Furthermore, users can only access and modify the state of the object by calling special methods. This allows
the object to protect itself from misuse.  Encapsulation is everywhere. Think about your everyday DVD player.
Do you know how to build one? Do you know all its internal workings? Yet you probably use it all the time.

C# supports encapsulation via the class construct and various keywords that control the access level of a class
member.  When you create a class, you are creating a custom type that you use to declare variables.  An object
is the actual bits and bytes of this class in memory. You can think of a class as a blueprint for objects.  The
blueprint analogy also applies to the extent that you can (and often do) use a single class to create many objects.

To promote encapsulation, you should make class fields private.  Since nothing outside the class can access
private members, the data is safe from misuse.  It is common practice to implement special public methods that
allow
controlled access to the private fields.  In some circles, these methods are called getters and setters, or in
more highbrow circles: accessors and mutators.

// Traditional accessor and mutator for private data.
public class Employee
{
  private double mWage;

  // Accessor.
  public double GetWage() { return mWage; }

  // Mutator.
  public void SetWage(double wage)
  {
    // Enforce business rule: wage value must be less than $20.
    if (wage < 20)
    {
       mWage = wage;
    }
   }
...
}


Here is some code that uses the accessor and mutator:


// Accessor / mutator usage.
static void Main(string[] args)
{
  Employee emp = new Employee();
  emp.
SetWage(15.5);
  Console.WriteLine("Employee's wage is: {0}", emp.
GetWage());
}


C# supplies a syntactical construct called a property that makes writing accessors and mutators more concise.   
In fact, it is a .NET best practice to encapsulate state data using property syntax (not via traditional get / set
methods).  Here is the
Wage property syntax that is equivalent to the traditional accessor/mutator technique.


public class Employee
{
 private double mWage;

 // Lack of parenthesis means this a property instead of a method

 public double Wage  
 {
   get { return mWage; }
   set
   {

     // Enforce business rule: wage value must be less than $20.

     if (value < 20)
     {
       mWage = value;
     }
   }
 }
...
}


To the object consumer, a property looks like a publicly exposed field.  In reality, the class developer controls
all access by implementing validation logic within the property.


// Property usage

static void Main(string[] args)
{
  Employee emp = new Employee();

  // Wage set block invoked. 15.5 passed as value argument

  emp.Wage = 15.5;  

  // Wage get block invoked

  Console.WriteLine("Employee's wage is: {0}", emp.
Wage);
}


You can also create read-only and write-only properties:


// Read-only properties have a get block but no set block.

public string Name
{
  get {return mName;}
}



// Write-only properties have a set block but no get block.
public double Hours
{
  set {mHours = value;}
}


It is also possible to define unique access modifiers for a single property (for example, a public get and
protected set).  The access modifier used on the property definition will be the least restrictive, while the get /
set scope will specify the more restrictive.  Consider the following
Car class definition with a single Speed
property:


public class Car
{
 private int currSpeed;

 
// Anyone can get the speed,
 // but only the Car and derived types can set it.
 public
int Speed
 {
   get {return  currSpeed;}      
   
protected set { currSpeed = value; }
 }
}

Encapsulation and Class Development
Table of Contents
C# Tutorial | C#.NET Tutorial | Custom Classes Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services