Section 9.11. Const and ReadOnly Members


9.11. Const and ReadOnly Members

Visual Basic allows you to create constantsmembers whose values cannot change during program execution. To create a constant instance variable of a class, declare that member as either Const or ReadOnly. An instance variable declared as Const must be initialized in its declaration; an instance variable declared as ReadOnly can be initialized either in its declaration or in the class constructor. Const values must be initialized at compile time; whereas ReadOnly values are not initialized until runtime. Neither a Const nor a ReadOnly value can be modified once initialized.

Error-Prevention Tip 9.4

If a variable's value should never change, making it a constant prevents it from changing. This helps eliminate errors that might occur if the value of the variable were to change.


Common Programming Error 9.7

Declaring an instance variable as Const but failing to initialize it in that declaration is a compilation error.


Common Programming Error 9.8

Assigning a value to a Const instance variable is a compilation error.


Const members must be initialized at compile time; thus, they can be initialized only to constant values, such as integers, string literals, characters and other Const members. Constant members with values that cannot be determined at compile time must be declared ReadOnly. Recall that a ReadOnly member can be assigned a value only once, either when it is declared or within the class's constructor (the Shared constructor for Shared ReadOnly members and a non-Shared constructor for non-Shared ReadOnly members).

Common Programming Error 9.9

Declaring an instance variable as ReadOnly and attempting to use it before it is initialized is a logic error.


Common Programming Error 9.10

A Shared ReadOnly variable cannot be initialized in an instance constructor for that class, and a ReadOnly instance variable cannot be initialized in a Shared constructor for that class. Attempting to define a ReadOnly variable in an inappropriate constructor is a compilation error.


Common Programming Error 9.11

Declaring a Const member as Shared is a compilation error, because a Const member is Shared implicitly.


Common Programming Error 9.12

Declaring a ReadOnly member as Const is a compilation error, because these two keywords are not allowed to be combined in a variable declaration.


Class CircleConstants with Const and ReadOnly Instance Variables

Class CircleConstants (Fig. 9.12) demonstrates constants. Line 4 creates constant PI using keyword Const and assigns to PI the Double value 3.14159an approximation of π. We could have used pre-defined constant PI of class Math (Math.PI) as the value, but we wanted to demonstrate how you can create your own Const instance variables. The com-piler must be able to determine a Const's value to be able to initialize a Const instance variable with that value. The value 3.14159 is acceptable (line 4), but the expression

 Convert.ToDouble("3.14159") 


generates a compilation error if used in place of that value. Although this expression uses a constant value (String literal "3.14159") as an argument and produces the same numeric value, a compilation error occurs, because the compiler cannot evaluate executable code (such as a method call). This restriction is lifted with ReadOnly members, which are initialized at runtime. Note that line 9 assigns the value of the constructor parameter radiusValue to ReadOnly member RADIUS at runtime. We could also have used a method call, such as Convert.ToDouble, to assign a value to this ReadOnly member.

Figure 9.12. Constants used in class CircleConstants.

  1  ' Fig. 9.12: CircleConstants.vb  2  ' Encapsulate constants PI and radius.  3  Class CircleConstants  4     Public Const PI As Double = 3.14159 ' PI is a Const instance variable  5     Public ReadOnly RADIUS As Integer ' radius is uninitialized constant   6  7     ' constructor of class CircleConstants  8     Public Sub New(ByVal radiusValue As Integer)  9        RADIUS = radiusValue ' initialize ReadOnly constant 10     End Sub ' New 11  End Class ' CircleConstants 

Using Const and ReadOnly

Module ConstAndReadOnly (Fig. 9.13) demonstrates the Const and ReadOnly values. Line 5 creates a Random object that is used in line 8 to generate a random Integer in the range 120 that corresponds to a circle's radius. This enables each program execution to produce different output. The random value is passed to the CircleConstants constructor to initialize a CircleConstants object. Lines 1113 access the ReadOnly variable RADIUS through a reference to object circle, and compute and display the circle's circumference. This calculation employs the Public Const member PI, which we access in line 13 through its class name CircleConstants. Recall that Const members are implicitly Shared; thus we can access a Const member with its class name followed by the dot separator even when no objects of the class are present.

Figure 9.13. Const and ReadOnly class members demonstration.

  1  ' Fig. 9.13: ConstAndReadOnly.vb  2  ' Demonstrates Const and ReadOnly members.  3  Module ConstAndReadOnly  4     Sub Main()  5        Dim random As New Random() ' create Random object  6  7        ' create CircleConstants object with random radius  8        Dim circle As New CircleConstants(random.Next( 1, 20))  9 10        ' calculate the circle's circumference 11        Console.WriteLine("Radius = "& circle.RADIUS & vbCrLf & _ 12           "Circumference = " & String.Format("{0:F3}", _ 13           2 * CircleConstants.PI * circle.RADIUS)) 14     End Sub ' Main 15  End Module ' ConstAndReadOnly 

 Radius = 9 Circumference = 56.549 



ReadOnly and WriteOnly Properties

Recall from Chapter 4 that not all properties need to have Get and Set accessorsa property with only a Get accessor is called a read-only property and must be declared using keyword ReadOnly; a property with only a Set accessor is called a write-only property and must be declared using keyword WriteOnly.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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