const vs. readonly
I believe that author means the following:
Consider example:
public class A {
public const int a = Compute();
private static int Compute(){
/*some computation and return*/
return some_computed_value;
}
}
this, will not compile, as you have to have constant value to assign to a
.
So this is a meaning of compile-time constant .
Instead if you change this to
public class A {
public readonly int a = Compute();
private static int Compute(){
/*some computation and return*/
return some_computed_value;
}
}
this will compile. It at runtime makes a computation and assign it to a
.
This is a meaning of runtime constant
As you yourself note, that term is not used in the language specification etc. So; blame that book! I would call it a "readonly field", because that is what it is - where the definition of "readonly" here relates to the initializer/constructor, and is limited to regular code. For example, even readonly fields are changeable...
// how to annoy your colleagues...
typeof(string).GetField("Empty").SetValue(null, " ");
(Note, this no longer works on recent CLR versions - the JIT presumably replaces the field-load with a ldstr - but it genuinely did for a very long time)
(more genuine reasons to do this on objects relate to deserialization)
A readonly variable can only be changed in its constructor and can be used on complex objects. A constant variable cannot be changed at runtime, but can only be used on simple types like Int, Double, String. Runtime constant is somewhat accurate, but confuses the issue, there are very explicit differences between a constant and a readonly, and so naming one similar to another is probably not a good idea, even though often they are used to the same purpose.
A quick summary of the differences here