const and readonly ModifiersTwo more field modifiers are related to encapsulation. The first is the const modifier, which you already encountered when declaring local variables. The second is readonly. constJust as with const local variables, a const field contains a compile-time-determined value that cannot be changed at runtime. Values such as pi make good candidates for constant field declarations. Listing 5.28 shows an example of declaring a const field. Listing 5.28. Declaring a Constant Field
Constant fields are static automatically, since no new field instance is required for each object instance. Declaring a constant field as static explicitly will cause a compile error. readonlyUnlike const, the readonly modifier is available only for fields (not for local variables) and it declares that the field value is modifiable only from inside the constructor or directly during declaration. Listing 5.29 demonstrates how to declare a readonly field. Listing 5.29. Declaring a Field as readonly
Unlike constant fields, readonly fields can vary from one instance to the next. In fact, a readonly field's value can change from its value during declaration to a new value within the constructor. Furthermore, readonly fields occur as either instance or static fields. Another key distinction is that you can assign the value of a readonly field at execution time rather than just at compile time. Using readonly with an array does not freeze the contents of the array. It freezes the number of elements in the array because it is not possible to reassign the readonly field to a new instance. However, the elements of the array are still writeable. |