Constant value not changing when recompiling referenced assembly

后端 未结 2 821
日久生厌
日久生厌 2020-12-20 13:33

I have this code in an assembly:

public class Class1
{
    public const int x = 10;
}

and in a different assembly I have:<

相关标签:
2条回答
  • 2020-12-20 14:04

    Constants values in C# are in-lined in place where they are used. I.e. line Console.WriteLine(Class1.x); will be compiled to Console.WriteLine(10);. Generated IL-code will look like:

      .entrypoint
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldc.i4.s   10  // here just integer value 10 is loaded on stack
      IL_0003:  call       void [mscorlib]System.Console::WriteLine(int32)
    

    There will not be any link to Class1. So, until you re-compile Main assembly, it will have in-lined value 10. MSDN has warning about this case of constants usage:

    Don’t create a constant to represent information that you expect to change at any time. For example, don’t use a constant field to store the price of a service, a product version number, or the brand name of a company. These values can change over time, and because compilers propagate constants, other code compiled with your libraries will have to be recompiled to see the changes.

    They mention that constant expressions are evaluated only at compile time. I.e. Class1.x will be evaluated at Main assembly compile time to value 10. And without re-compilation that value will not change. But unfortunately it does not clearly explains reason of such behavior (to me at least).

    BTW Named and Optional parameters values are also in-lined in place where method is called, and you also need to re-compile caller assembly to update values.

    0 讨论(0)
  • 2020-12-20 14:11

    This is a technique called constant folding used in compiling. In short, the compiler look for values that can be determined at compile time, computes those values, and write them directly in the exe file. This speeds up the execution of the final machine code. This technique applies to other many compiled languages, such as C, C++ as well.

    0 讨论(0)
提交回复
热议问题