Posts

Showing posts from March, 2020

Static Readonly instead of Const in C#

I have always considered it a best practice to use  static readonly  instead of  const  in C#. Here’s why… The  const  keyword tells the compiler to replace the constant token in your code with the literal value you have defined for the constant. You can see this if you look at the IL: The C# code… const string HELLO = "Hello" ; ... Console . WriteLine ( HELLO ); Console . WriteLine ( HELLO ); Compiles to the IL… .field private static literal string HELLO = "Hello" ... IL_0001: ldstr "Hello" IL_0006: call void [System.Console]System.Console::WriteLine(string) IL_000b: nop IL_000c: ldstr "Hello" IL_0011: call void [System.Console]System.Console::WriteLine(string) Notice that the literal  "Hello"  is loaded twice. Using  static readonly  provides us similar semantics–a global value that cannot be changed–but rather than references being replaced with literals by the compiler, it remains ...