Back to notes -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    A BankAccount class with a disciplined Balance property.Lecture 5 - slide 7 : 29
Program 5
using System;

public class BankAccount {

   private string owner;
   private decimal balance;  
   private bool readMode;    

   public BankAccount(string owner, decimal balance) {
      this.owner = owner; 
      this.balance = balance;
      this.readMode = true;
   }

   public decimal Balance {
     get {if (readMode){
             readMode = false;
             return balance;
          }
          else throw new Exception("Cannot read now!");
         }
     set {if (!readMode){
             balance = value;
             readMode = true;
          }
          else throw new Exception("Cannot write now!");
         }
   }   

   public override string ToString() {
      return owner + "'s account holds " +
            + balance + " kroner";
   }
} 
This program illustrate what is possible to do
with properties. Notice, however, that the illustrated
use of properties is a little tricky, and not typical.
 
 
balance (instance var) accessed by Balance property.
Used in the property to enforce alternating read/write.
 
 
 
 
 
 
 
The variable readMode ensures that alternating
reads and writes are enforced. First reading is 
allowed, and next writing is allowed. This 
makes it attractive to manipulate the account via
assignments like obj.Balance = obj.Balance + someAmount.