Figure 1 Abstracting Data Fields
class Employee {
private String Name; // field is now private
private Int32 Age; // field is now private
public String GetName() {
return(Name);
}
public void SetName(String value) {
Name = value;
}
public Int32 GetAge() {
return(Age);
}
public void SetAge(Int32 value) {
if (value <= 0)
throw(new ArgumentException("Age must be greater than 0");
Age = value;
}
}
Figure 2 Using
Get and Set Properties
class Employee {
private String _Name; // prepended '_' to avoid conflict
private Int32 _Age; // prepended '_' to avoid conflict
public String Name {
get { return(_Name); }
set { _Name = value; } // 'value' always identifies the new value
}
public Int32 Age {
get { return(_Age); }
set {
if (value <= 0) // 'value' always identifies the new value
throw(new ArgumentException("Age must be greater than 0");
_Age = value;
}
}
}
Figure 3 Using
Index Properties
class BitArray {
private Byte[] byteArray;
public BitArray(int numBits) {
if (numBits <= 0)
throw new ArgumentException("numBits must be > 0");
byteArray = new Byte[(numBits + 7) / 8];
}
public Boolean this[Int32 bitPosition] {
get {
if ((bitPosition < 0) ||
(bitPosition > byteArray.Length * 8 - 1))
throw new IndexOutOfRangeException();
return((byteArray[bitPosition / 8] &
(1 << (bitPosition % 8))) != 0);
}
set {
if ((bitPosition < 0) ||
(bitPosition > byteArray.Length * 8 - 1))
throw new IndexOutOfRangeException();
if (value) {
byteArray[bitPosition / 8] = (Byte)
(byteArray[bitPosition / 8] |
(1 << (bitPosition % 8)));
} else {
byteArray[bitPosition / 8] = (Byte)
(byteArray[bitPosition / 8] &
~(1 << (bitPosition % 8)));
}
}
}
}