Information Technology Reference
In-Depth Information
The readonly Modifier
A field can be declared with the
readonly
modifier. The effect is similar to declaring a field as
const
, in that once the value is set, it cannot be changed.
Wh le a
const
field can only be initialized in the field's declaration statement, a
readonly
field can have its value set in either of the following:
-
The field declaration statement—like a
const
.
Any of the class constructors. If it is a
static
field, then it must be done in the
static
constructor.
-
While the value of a
const
field must be determinable at compile time, the value of a
readonly
field can be determined at run time. This additional freedom allows you to set
different values in different constructors!
Unlike a
const
, which always acts like a static, the following is true of a
readonly
field:
-
It can be either an instance field or a static field.
-
It has a storage location in memory.
For example, the following code declares a class called
Shape
, with two
readonly
fields.
Field
PI
is initialized in its declaration.
Field
NumberOfSides
is set to either 3 or 4, depending on which constructor is called.
class Shape
{
Keyword
Initialized
↓
↓
readonly double PI = 3.1416;
readonly int NumberOfSides;
↑
↑
Keyword
Not initialized
public Shape(double side1, double side2) // Constructor
{
// Shape is a rectangle
NumberOfSides = 4;
↑
...
Set in constructor
}
public Shape(double side1, double side2, double side3) // Constructor
{
// Shape is a triangle
NumberOfSides = 3;
↑
...
Set in constructor
}
}