Free mag vol1 | Page 247

CHAPTER 5  UNDERSTANDING ENCAPSULATION ***** Fun with Static Data ***** In static ctor! Interest Rate is: 0.04 Interest Rate is: 0.08 Here are a few points of interest regarding static constructors: • A given class may define only a single static constructor. In other words, the static constructor cannot be overloaded. • A static constructor does not take an access modifier and cannot take any parameters. • A static constructor executes exactly one time, regardless of how many objects of the type are created. • The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller. • The static constructor executes before any instance-level constructors. Given this modification, when you create new SavingsAccount objects, the value of the static data is preserved, as the static member is set only one time within the static constructor, regardless of the number of objects created.  Source Code The StaticDataAndMembers project is included under the Chapter 5 subdirectory. Defining Static Classes It is also possible to apply the static keyword directly on the class level. When a class has been defined as static, it is not creatable using the new keyword, and it can contain only members or data fields marked with the static keyword. If this is not the case, you receive compiler errors.  Note Recall that a class (or structure) that only exposes static functionality is often termed a utility class. When designing a utility class, it is good practice to apply the static keyword to the class definition. At first glance, this might seem like a fairly odd feature, given that a class that cannot be created does not appear all that helpful. However, if you create a class that contains nothing but static members and/or constant data, the class has no need to be allocated in the first place! To illustrate, create a new Console Application named SimpleUtilityClass. Next, define the following class: 183