318 Object-Based Programming Chapter 8 Common Programming Error (Web hosting unlimited bandwidth)

318 Object-Based Programming Chapter 8 Common Programming Error 8.10 Declaring a class data member as readonly and attempting to use it before it is initialized is a logic error. Members that are declared as constmust be assigned values at compile time. Therefore, constmembers can be initialized only with other 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 with keyword readonly. We mentioned previously that a readonlymember can be assigned a value only once, either when it is declared or within the constructor of the class. When initializing a static readonlymember in a constructor, a staticconstructor must be used. Figure 8.15 demonstrates constants. The program consists of two classes class Constants (lines 8 22) defines two constants, and class UsingConstAndReadonly (lines 25 43) demonstrates the constants in class Constants. 1 // Fig. 8.15: UsingConstAndReadOnly.cs 2 // Demonstrating constant values with const and readonly. 3 4 using System; 5 using System.Windows.Forms; 6 7 // Constants class definition 8 public class Constants 9 { 10 // create constant PI 11 public const double PI = 3.14159; 12 13 // radius is a constant 14 // that is uninitialized 15 public readonly int radius; 16 17 public Constants( int radiusValue ) 18 { 19 radius = radiusValue; 20 } 21 22 } // end class Constants 23 24 // UsingConstAndReadOnly class definition 25 public class UsingConstAndReadonly 26 { 27 // method Main creates Constants 28 // object and displays its values 29 static void Main( string[] args ) 30 { 31 Random random = new Random(); 32 33 Constants constantValues = 34 new Constants( random.Next( 1, 20 ) ); 35 Fig. 8.15 Fig. 8.15Fig. 8.FiFi15g. 8.15g. 8.15constand readonlyclass member demonstration. (Part 1 of 2.)
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Leave a Reply