Possible Duplicate:
What is the difference between const and readonly?
So from what I read, in C#, const
and static readonly
will both make a value unalterable during the execution of a program.
However, const
should be used with quantities which are unlikely to ever change (e.g. pi, radius of earth, litters per gallon etc.).
On the other hand, static readonly
should be used with values that currently are constant but might/will change in the future (e.g. software version, a multiplier in an algorithm etc.).
Have I got it right?
readonly is a constant defined at runtime. const is used to create a constant at compile time. readonly field value can be changed after declaration. const field value cannot be changed after declaration.
The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.
A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a 'const' is always constant but 'readonly' is read-only once it is assigned.
const is a constant value, and cannot be changed. It is compiled into the assembly. static means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly ). So if the values are never changed, use consts.
I don't know about your second item (I would probably use a constant for a software version or an algorithm… constant) but there is one key difference between the two: const
can only hold basic types such as string
, bool
, or numeric types. static readonly
can hold any object. So, for example, I often use static readonly
to store resources like Bitmap
objects. Those cannot be const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With