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

public class BankAccount {    

   private string owner;
   private decimal[] contributions;
   private int nextContribution;

   public BankAccount(string owner, decimal balance) {
      this.owner = owner; 
      contributions = new decimal[100];
      contributions[0] = balance;
      nextContribution = 1;
   }

   public decimal Balance {                           
     get {decimal result = 0;                         
          foreach(decimal ctr in contributions)       
             result += ctr;                           
          return result;                              
         }
   }    

   public void Deposit(Decimal amount){
     contributions[nextContribution] = amount;
     nextContribution++;
   } 

   public void Withdraw(Decimal amount){
     contributions[nextContribution] = -amount;
     nextContribution++;
   } 

   public override string ToString() { 
      return owner + "'s account holds " +
            + Balance + " kroner";                  
   }
} 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
This is the place to watch.
The getter adds all elements in
the array together and it returns
the sum as result of the 
property
 
 
 
This method adds to the balance
by putting amount into the contributions
array.
 
 
In the same way, this method adds to the balance
by putting -amount into the contributions
array.
 
 
 
 
Notice that we refer to the property Balance here