Understanding the const keyword in C#

Written: 19 December 2013

Lets consider a very simple class PI, we will define a public const property called pi.

public class PI
    public const double pi = 3.14d;        

We compile this and make it a dll.

We are now going to use this dll in a program. Below is the code for the program.

class Program
        static void Main(string[] args)
            double myPi = ConstClassTest.PI.pi;
            Console.WriteLine("The value of pi : {0}", myPi);            

We will add the pi.dll as an reference to this program.

Output of this program:

 The value of pi: 3.14

Nothing surprising here.

Now lets open up the pi.dll in ildasm.exe to view the MSIL generated. Checkout how pi is declared:

pi:public static literal float64

Thats right, its static literal. If you double clik on it you will see this:

.field public static literal float64 pi = float64(3.1400000000000001)

This simply means that the value 3.14 is hardcoded into the dll.

Lets now see what did the compiler do with the program. If you open the Main : void(string[]), this is what you will see

.method private hidebysig static void  Main(string[] args) cil managed
  // Code size       33 (0x21)
  .maxstack  2
  .locals init ([0] float64 myPi)
  IL_0000:  ldc.r8     3.1400000000000001
  IL_0009:  stloc.0
  IL_000a:  ldstr      "The value of pi : {0}"
  IL_000f:  ldloc.0
  IL_0010:  box        [mscorlib]System.Double
  IL_0015:  call       void [mscorlib]System.Console::WriteLine(string,
  IL_001a:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  IL_001f:  pop
  IL_0020:  ret
} // end of method Program::Main

Checkout IL_0000: ldc.r8 3.1400000000000001, the compiler basically copied over the value of pi from pi.dll. In other words, the compiler replaced the ConstClassTest.PI.pi variable with actual value that is 3.14.

Now lets make a change to our pi dll. We want to make our pi more precise. Change public const double pi = 3.14d to public const double pi = 3.1415d and recompile the dll. Copy the newly created dll to the program bin folder and replace the older one with the new one. Now run the program again with out recompiling it. Here is the output:

 The value of pi: 3.14

The output did not change and it should not be a surprise as the compiler had copied over the value during compilation. We will have to recompile our program to get the updated value from the pi.dll.

Domain Registrations starting at $9.98*