vote buttons
2
1
beginner
0
intermediate
0
advanced
30-Nov-2014 06:04 UTC
K Bonneau
350

1 Answers

vote buttons
3
The main difference between const and readonly is that a const variable is a compile time constant, while a readonly variable is a runtime constant.

A const value must be assigned with its declaration and its value should be a known compile time constant. 

A readonly variable can either be assigned during declaration or in a constructor. Hence depending on which constructor is used, different instances can have different values for a readonly variable.

A note of caution using consts:
Consider a scenario when you have a public const variable in Assembly A with value x, and another Assembly B refers to that value. When these are compiled, Assembly B has the value of the const variable baked into it. If we now change the value of the const variable to y in Assembly A, and only compile and deploy Assembly A, Assembly B wont see this new value. Assembly B must be recompiled so the value inside the assembly gets updated. This is not the case with readonly variables.

30-Nov-2014 06:04 UTC
K Bonneau
350