const and readonly Modifiers


const and readonly Modifiers

Two 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.

const

Just 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

 class ConvertUnits {    public const float CentimetersPerInch = 2.54F;    public const int CupsPerGallon = 16;    // ... } 

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.

readonly

Unlike 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

 class Employee {   public Employee(int id)   {       Id = id;                                             }   // ...   public readonly int Id;                                   public void SetId(int newId)   {      // ERROR: readonly fields cannot be set                   //        outside of the constructor.                     // Id = newId                                            }     // ... } 

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.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net