Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

c# - Constant value not changing when recompiling referenced assembly

I have this code in an assembly:

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

and in a different assembly I have:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Class1.x);
        Console.ReadKey();
    }
}

Of course the output was 10, but then I changed x to 20:

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

I recompiled the assembly and moved it to my command line program's bin directory. However, the output of my program was still 10, until I compiled assembly containing the main function.

Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...