They say the difference between readonly and const is that const is compile-time (while readonly is run time). But what exactly does that mean, The fact that it's compile time? Everything gets compiled to byte code doesn't it?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
One consequence of const being compile time is that changes to the const in one assembly does not get picked up automatically by other assemblies without recompiling them all.
Eg:
At runtime, Assembly B thinks the value of the const is still 10, not 20.
If it were readonly, it would pick up the new value.
It just means that every instance of the member marked as
const
will be replaced with its value during compilation, while readonly members will be resolved at run-time.Typically, a "compile-time constant" would refer to a constant literal value that the compiler would resolve. The code that the compiler generates will have the constnat value available as an immediate operand, instead of having to load it from memory.
Although the answer that Julio provided is valid from the effects of setting a variable as a constant or a read only, there are a great deal of difference between the two declarations.
While many people simply state the obvious that the value of a constant is resolved at the compilations, while a read only value will be resolved only during the run time, the main point resides where the reference is quept.
Depending on the data type of the constant, it will be either replaced at the command evocation, or stored in the
HEAP
and referenced by a pointer.For instance, the code:
may be resolved at the compilation time as simply:
On the other hand a read only field is always stored on the
STACK
and referenced by a pointer.A const can only be defined during its declaration. A readonly can be defined during its declaration or in a constructor. So a readonly variable can have different values according to the constructor used to initialize it.
It means that const variables get written to the location they are referenced from. So, say you have an 2 libraries, one with a
const
variable:The variable is actually written, at compile time, into B. The difference is, if you recompile A but not B, B will have the "old" value. This won't happen with
readonly
variables.