const or readonly

  • Thread starter Thread starter Axel Dahmen
  • Start date Start date
A

Axel Dahmen

Hi,

can someone please enlighten me on the difference between a "const" and a
"readonly" declaration?

TIA,
Axel Dahmen
 
Axel Dahmen said:
can someone please enlighten me on the difference between a "const" and a
"readonly" declaration?

If a field is "const", anything which refers to the field has the value
of the constant placed into the IL - there is no runtime reference to
it. This has one potentially nasty side-effect - if you change the
value of a const field in one assembly (at compile-time, I mean) then
any other assemblies which need to see the "new" value need to be
recompiled - they won't try to "get" the value from the originating
assembly at runtime.

Consts are probably more performant (although it's unlikely to be
significant), but can only be applied to a limited range of types.

Of course, consts are also limited to those values which are known at
compile-time.
 
readonly can be set to a value in the constructor. Const cannot - its value
must be provided inline with the declaration.
 
Back
Top