Constants and readonly fields have different binary versioning semantics. When an expression references a constant, the value of the constant is obtained at compile-time, but when an expression references a readonly field, the value of the field is not obtained until run-time. Consider an application that consists of two separate projects:
namespace Project1 { public class Utils { public static readonly int X = 1; } } namespace Project2 { class Test { static void Main() { Console.WriteLine(Project1.Utils.X); } } }
The Project1
and Project2
namespaces denote two projects that are compiled separately. Because Project1.Utils.X
is declared as a static readonly field, the value output by the Console.WriteLine
statement is not known at compile-time, but rather is obtained at run-time. Thus, if the value of X
is changed and Project1
is recompiled, the Console.WriteLine
statement will output the new value even if Project2
isn’t recompiled. However, had X
been a constant, the value of X
would have been obtained at the time Project2
was compiled, and would remain unaffected by changes in Project1
until Project2
is recompiled.