const or readonly

A

Axel Dahmen

Hi,

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

TIA,
Axel Dahmen
 
J

Jon Skeet [C# MVP]

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.
 
M

Marina

readonly can be set to a value in the constructor. Const cannot - its value
must be provided inline with the declaration.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top