开发者

What does compile time 'const' mean?

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 fac开发者_如何学运维t that it's compile time? Everything gets compiled to byte code doesn't 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:

// Library A
const int TEST = 1;

// Library B
void m ()
{
   Console.WriteLine(A.TEST);
}

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.


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.


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:

const int x = 3;
int y = 3 * x;

may be resolved at the compilation time as simply:

int y = 3 * 3;

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.


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.


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:

  1. Assembly A has public const of int = 10
  2. Assembly B refers to that const.
  3. Both compiled. Now Assembly A const changed to 20, redeployed.
  4. Assembly B not recompiled.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜