Free mag vol1 | Page 245

CHAPTER 5  UNDERSTANDING ENCAPSULATION  Note It is a compiler error for a static member to reference nonstatic members in its implementation. On a related note, it is an error to use the this operator in a static member as “this” implies an object! Defining Static Constructors A typical constructor is used to set the value of an object’s instance-level data at the time of creation. However, what would happen if you attempted to assign the value of a static point of data in a typical constructor? You might be surprised to find that the value is reset each time you create a new object! To illustrate, assume you have updated the SavingsAccount class constructor as follows (also note we are no longer assigning the currInterestRate field inline): class SavingsAccount { public double currBalance; public static double currInterestRate; // Notice that our constructor is setting // the static currInterestRate value. public SavingsAccount(double balance) { currInterestRate = 0.04; // This is static data! currBalance = balance; } ... } Now, assume you have authored the following code in Main(): static void Main( string[] args ) { Console.WriteLine("***** Fun with Static Data *****\n"); // Make an account. SavingsAccount s1 = new SavingsAccount(50); // Print the current interest rate. Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate()); // Try to change the interest rate via property. SavingsAccount.SetInterestRate(0.08); // Make a second account. SavingsAccount s2 = new SavingsAccount(100); } // Should print 0.08...right?? Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate()); Console.ReadLine(); 181