May 22, 2008

The Constant Fact : Const Vs Static ReadOnly field

One fact about constant, that we all know, is it's value can never be changed.
Here goes another one.... The constant field is statically replaced by the compiler at the compile time wherever it is found.


circleArea = System.Math.PI * 2 * r;
compiled to
double circleArea = 6.28318 * r;

Said that, suppose you have following expression in your one assembly "Lib"

public const int DataGridPageSize = 50;

And you are referring this assembly in your application "App". Now if you compile the solution the DataGridPageSize will be replaced by 50 in your application. But, if you change the DataGridPageSize value to 100 and compile only the assembly "Lib" and forgot to compile the application "App" then your application still has the old value 50 and not the 100 unless you recompile the "App" application.

But if you have used readonly static field you are safe in above scenario as it is not statically replaced at compile time as the constants are.

Submit this story to DotNetKicks