CHAPTER 5 UNDERSTANDING ENCAPSULATION
If you execute the previous Main() method, you would see that that the currInterestRate variable is
reset each time you create a new SavingsAccount object, and it is always set to 0.04. Clearly, setting the
value of static data in a normal instance-level constructor sort of defeats the whole purpose. Every time
you make a new object, the class-level data is reset! One approach to setting a static field is to use
member initialization syntax, as you did originally:
class SavingsAccount
{
public double currBalance;
// A static point of data.
public static double currInterestRate = 0.04;
...
}
This approach will ensure the static field is assigned only once, regardless of how many objects you
create. However, what if the value for your static data needed to be obtained at runtime? For example, in
a typical banking application, the value of an interest rate variable would be read from a database or
external file. To perform such tasks requires a method scope such as a constructor to execute the code
statements.
For this very reason, C# allows you to define a static constructor, which allows you to safely set the
values of your static data. Consider the following update to our class:
class SavingsAccount
{
public double currBalance;
public static double currInterestRate;
public SavingsAccount(double balance)
{
currBalance = balance;
}
// A static constructor!
static SavingsAccount()
{
Console.WriteLine("In static ctor!");
currInterestRate = 0.04;
}
...
}
Simply put, a static constructor is a special constructor that is an ideal place t o initialize the values
of static data when the value is not known at compile time (e.g., you need to read in the value from an
external file, a database, generate a random number, or whatnot). If you were to rerun the previous
Main() method, you would find the output you expect. Note that the message “In static ctor!” only prints
out one time, as the CLR calls all static constructors before first use (and never calls them again for that
instance of the application):
182