Free mag vol1 | Page 273

CHAPTER 5  UNDERSTANDING ENCAPSULATION } } Again, any attempt to make assignments to a field marked readonly outside the scope of a constructor results in a compiler error: class MyMathClass { public readonly double PI; public MyMathClass () { PI = 3.14; } // Error! public void ChangePI() { PI = 3.14444;} } Static Read-Only Fields Unlike a constant field, read-only fields are not implicitly static. Thus, if you want to expose PI from the class level, you must explicitly make use of the static keyword. If you know the value of a static readonly field at compile time, the initial assignment looks very similar to that of a constant (however in this case, it would be easier to simply use the const keyword in the first place, as we are assigning the data field at the time of declaration): class MyMathClass { public static readonly double PI = 3.14; } class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Const *****"); Console.WriteLine("The value of PI is: {0}", MyMathClass.PI); Console.ReadLine(); } } However, if the value of a static read-only field is not known until runtime, you must make use of a static constructor as described earlier in this chapter: class MyMathClass { public static readonly double PI; static MyMathClass() { PI = 3.14; } } 209