Chapter 8 Object-Based Programming 319 36 MessageBox.Show( “Radius (My space web page)

Chapter 8 Object-Based Programming 319 36 MessageBox.Show( “Radius = ” + constantValues.radius + 37 “nCircumference = ” + 38 2 * Constants.PI * constantValues.radius, 39 “Circumference” ); 40 41 } // end method Main 42 43 } // end class UsingConstAndReadOnly Fig. 8.15 Fig. 8.15Fig. 8.FiFi15g. 8.15g. 8.15constand readonlyclass member demonstration. (Part 2 of 2.) Line 11 in class Constantscreates constant PIusing keyword constand initializes PIwith the doublevalue 3.14159 an approximation of p that the program uses to calculate the circumferences of circles. Note that we could have used the predefined constant PI of class Math (Math.PI) as the value, but we wanted to demonstrate how to define a constvariable explicitly. The compiler must be able to determine a constvariable s value at compile time; otherwise, a compilation error will occur. For example, if line 11 initialized PIwith the expression: Double.Parse( “3.14159″ ) the compiler would generate an error. Although the expression uses string literal “3.14159″(a constant value) as an argument, the compiler cannot evaluate the method call Double.Parseat compile time. Variables declared readonly can be initialized at execution time. Line 15 declares readonly variable radius, but does not initialize it. The Constants constructor (lines 17 20) receives an intvalue and assigns it to radiuswhen the program creates a Constantsobject. Note that radius also can be initialized with a more complex expression, such as a method call that returns an int. Class UsingConstAndReadonly (lines 25 43) uses the const and readonly variables of class Constants. Lines 33 34 use a Randomobject to generate a random intbetween 1and 20that corresponds to a circle s radius, then pass that value to the Constants constructor to initialize the readonly variable radius. Lines 36 39 output the radius and circumference of a circle in a MessageBox. Line 36 uses Constants s reference contantValuesto access readonlyvariable radius. Line 38 computes the circle s circumference using const variable Constants.PI and readonlyvariable radius. Note that we use staticsyntax to access constvariable PI, because constvariables implicitly are static. 8.13 Indexers Sometimes a class encapsulates data that a program can manipulate as a list of elements. Such a class can define special properties called indexers that allow array-style indexed access to lists of elements. With conventional C# arrays, the subscript number must be an
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Leave a Reply