Partager via


.Net - const Vs readonly

In programming, some time we used "const", some time "readonly" constants. Why? Always we should be very cautious when using "const". why?

Here we are, while programming we should always trade off between performance vs flexibility. "const" is faster than "readonly". But "readonly" has more flexibility than "const". There are two types of constants

  1) Compile time constants
  2) Run time constants

Compile time constants

Compile time constants are replaced with exact value when it compiled. what is it mean? Well. When we declare a variable 

 public const int iUserCount = 500;

 
 and when we do some operation like
 for (int iCount = 0; iCount < iUserCount; iCount++)

Then x will actually get replaced in the compile time and if you see in the IL using assembler it will be 
for (int iCount = 0; iCount < 500 ; iCount++)

 

Run Time constants

When we use "readonly", it will not put the actual value instead of reference. Thats why it is slower than Compile time constants. But there is an advantage.
public readonly int iUserCount

1) With Const we can only declare primitive types and string. But with readonly we can declare all the types.
2) Runtime will be resolved at the runtime

Why we need very cautious about "const".

We should be very cautious about "const" when maintenance come into picture. The reason is, assume you have an assembly "A" where you have declared the
public const int iUserCount = 500; 

And in the Assembly "B" you are using the iUserCount in 

 for (int iCount = 0; iCount < iUserCount; iCount++). 

 

When compiling both, Assembly "B" will have the statement as 

 

for (int iCount = 0; iCount < 500; iCount++)

 

 

Later when you modify the iCount value as 1500 in assembly "A", 
then you have to recompile the assembly "B" also. 
until unless it will have the same 

 for (int iCount = 0; iCount < 500 ; iCount++) 

and produce wrong result. So maintenance become nightmare. 
So prefer readonly then const.

Happy Coding

Comments

  • Anonymous
    January 04, 2011
    The way you diclared in both runtime and compile constant are same. public const int iUserCount = 500;

  • Anonymous
    January 09, 2011
    Thanks.