0

const vs readonly

by volkanuzun 3. November 2008 08:36

Probably you already know that, const variable must be assigned a value when they are defined, however readonly values can be assigned a value during the construction time,after they are declared. Is there any other differences we should know? Well, let's look at a simple class:

 public class constref
    {
        public const int MagicNumber = 5;
        public readonly int MagicNumber2 = 10;
    } 

 

I declared a simple class, that has 2 public members, a const and a readonly, after i compile this, and using ildasm i look at dll file. Here is what i got for the constant value MagicNumber:


.field public static literal int32 MagicNumber = int32(0x00000005)
 

The variable is converted into a static int32 and its value is assigned right away. This means, if any other dll is referencing this dll,  when they dereference MagicNumber, at the compile time, the value of MagicNumber will be replaced to that library. Example: Assembly B is referencing the MagicNumber variable inside this constref class, and in the code it has something like: constref.MagicNumber => this will be replaced with 5 during compilation.  Which also means, if you change the constref code, and set the const value to 8, and dont compile Assembly B, assembly B will still have 5 (the old value).

Let's look at the readonly variable after compile: 


//this is the decleration:
.field public initonly int32 MagicNumber2

//this is the constructor created by compiler:
 .method public hidebysig specialname rtspecialname 
       instance void  .ctor() cil managed
{
  // Code size       16 (0x10)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.s   10
  IL_0003:  stfld      int32 constvsreadonly.constref::MagicNumber2
  IL_0008:  ldarg.0
  IL_0009:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000e:  nop
  IL_000f:  ret
} // end of method constref::.ctor

 

This time, the value isnt assigned at the declare time (even though that is what we did), but it is assigned at the constructor. One big advantage is that, if we apply the same scenario, Assembly  B derefencing the value of MagicNumber2, will be using runtime values. So we change the source for constref class, and assign 20 to MagicNumber2, and just recompile constref, we dont have to compile Assembly B to reflect the new changed

Tags: ,

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft