const is something that is better applied for true constants (the speed
of light, days of the week, number of seconds in a minute, etc, etc).
readonly is better suited for those things that require initialization,
which aren't necessarily known before the app is run. Good examples are the
local computer name, the startup time of a program, etc, etc. Basically,
things that won't change, but require some sort of work to find out when the
app is run.
Extracted from MSDN :
Note The readonly keyword is different from the const keyword. A const
field can only be initialized at the declaration of the field. A
readonly field can be initialized either at the declaration or in a
constructor. Therefore, readonly fields can have different values
depending on the constructor used. Also, while a const field is a
compile-time constant, the readonly field can be used for runtime
constants as in the following example:
public static readonly uint l1 = (uint) DateTime.Now.Ti cks;
Why C# has "readonly field" and "const value", while Java has only
"final"?
Are there any reasons for doing so?
Well, in Java if you have a static final value which is of an
appropriate type (numeric or string, IIRC) it's treated in the same way
as "const" is in C# - i.e. the value is compiled into any code
referencing it, rather than the value being fetched at execution time.
Personally, I prefer the way that C# makes that explicit.
Comment