There are many people who asking me again and again about this question,I've finally found some time to write about this and show you simple example for all of you out there so you can't forget this.
As we know (read somewhere but nor really remember) one is runtime and the other compile time...so here is the code:public const int IntConstField = 1;public const string StringConstField = "shani";public static readonly int IntROField = 1;public static readonly string StringROField = "shani";
and this the usage:Console.WriteLine(Class1.IntROField);Console.WriteLine(Class1.StringROField);Console.WriteLine(Class1.IntConstField);Console.WriteLine(Class1.StringConstField);
Isn't It look the same?so I disassemble this one for you...
IL_000a: ldsfld int32 [TestLib]TestLib.Class1::IntROFieldIL_000f: call void [mscorlib]System.Console::WriteLine(int32)IL_0014: ldsfld string [TestLib]TestLib.Class1::StringROFieldIL_0019: call void [mscorlib]System.Console::WriteLine(string)IL_000a: ldc.i4.1IL_000b: call void [mscorlib]System.Console::WriteLine(int32)IL_0010: ldstr "shani"IL_0015: call void [mscorlib]System.Console::WriteLine(string)
The first four rows show the Readonly, where you can see the ldsfld which is MSIL instruction for pushing the value of a static field into the stack!The other four rows show the Const, Where you can see ldc,ldstr instead of ldsfld which means that Const doesn't behave like Readonly, Const is very similar to to #define in c, don't have its own location as global, Const is just written as number/string (hard coded) at the compile time.
After we know this simple transformation at the compile time,we will see an example including two DLLs:
A: hold the const vars.B: uses A's const vars.When we made a change at A (changing one of the consts) we can't only compile it and replace the DLL at the bin directory, we should also compile this with the DLL who use it (B in our case).So it will change also the hard coded numbers!
PI, is a good const, but Unit Number or Dept Number (=180) isn't good enough.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.