Free mag vol1 | Page 244

CHAPTER 5  UNDERSTANDING ENCAPSULATION // Static members to get/set interest rate. public static void SetInterestRate(double newRate) { currInterestRate = newRate; } } public static double GetInterestRate() { return currInterestRate; } Now, observe the following usage: static void Main(string[] args) { Console.WriteLine("***** Fun with Static Data *****\n"); SavingsAccount s1 = new SavingsAccount(50); SavingsAccount s2 = new SavingsAccount(100); // Print the current interest rate. Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate()); // Make new object, this does NOT 'reset' the interest rate. SavingsAccount s3 = new SavingsAccount(10000.75); Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate()); Console.ReadLine(); } The output of the previous Main() is seen here: ***** Fun with Static Data ***** Interest Rate is: 0.04 Interest Rate is: 0.04 As you can see, when you create new instances of the SavingsAccount class, the value of the static data is not reset, as the CLR will allocate the static data into memory exactly one time. After that point, all objects of type SavingsAccount operate on the same value for the static currInterestRate field. When designing any C# class, one of your design challenges is to determine which pieces of data should be defined as static members, and which should not. While there are no hard and fast rules, remember that a static data field is shared by all objects of that type. Therefore, if you are defining a point of data that all objects should share between them, static is the way to go. Consider what would happen if the interest rate variable were not defined using the static keyword. This would mean every SavingsAccount object would have its own copy of the currInterestRate field. Now, assume you created 100 SavingsAccount objects, and need to change the interest rate. That would require you to call the SetInterestRate() method 100 times! Clearly, this would not be a very useful way to model “shared data.” Again, static data is perfect when you have a value that should be common to all objects of that category. 180