#603 – Using Constants Can Force Recompilation

Here’s an additional difference between a static readonly field and a constant.  Let’s say that you have a class that includes both a public static readonly field and a public constant.

public static readonly string ReadonlyMotto = "Man's Best Friend";
public const string ConstantMotto = "Man's Best Friend";

Now assume that you have two assemblies, as follows.

At this point, let’s say that you want to change the two elements that contain the dog mottos, i.e. the readonly field and the constant.  So you change the values and re-compile Dog.dll but do not re-compile DogViewer.exe.

At this point, something interesting happens at runtime if you run DogViewer.exe.

  • DogViewer sees the new value of the readonly field
  • DogViewer does not see the new value of the constant

This happens because when you compile code that uses a constant, the value of the constant is included in the generated code.