Constant and the readonly Modifier A class can define fields that are constant. To define a constant field, simply apply the const modifier and initialize the field to some value. You must initialize a constant field to another constant value, either a literal or a constant variable. Of course, once initialized, a constant field value can never change.
public class MyConstants { // Defining a non-constant field. private static string mName = "Homer"; // Initializing constants; these are valid. public const int c1 = 1; public const string c2 = "Another Constant"; public const string c3 = c2; // **** These are INVALID! ***** public const Employee c4 = new Employee(); public const int[] c5 = new int[]{1, 2, 3, 4}; public const string c6 = mName; public const string c7; // Const fields must be initialized. }
The compiler handles constants by "hard coding" the value into the CIL. Also note that constant members are implicitly static.
Use the readonly modifier to define a field that needs to be initialized with a non-constant value but must never change after initialization. The value of a read-only field is determined dynamically at runtime. In contrast, the value of a constant field is hardcoded into the CIL at compile time. Read-only fields are instance fields, whereas constant fields are implicitly static. You can combine the static and readonly modifiers.
public class MyConstants { // Defining a non-constant field. private static string mName = "Homer"; // **** These are INVALID! ***** public const Employee c4 = new Employee(); public const int[] c5 = new int[]{1, 2, 3, 4}; public const string c6 = mName; public const string c7; // const fields must be initialized. // All of the above work if you use readonly instead of const. public readonly Employee r1 = new Employee(); public readonly int[] r2 = new int[] {1, 2, 3, 4}; public readonly string r3 = mName; public readonly string r4;
public MyConstants() { // You can initialize readonly fields in a constructor but // not in any other method. r4 = "initializing a readonly field!"; } }
readonly and Constant
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.