Difference between const and readonly

  • Thread starter Thread starter Amit
  • Start date Start date
A

Amit

Hello,
I have a class where I store a lot of setting names. Right now they're all
declared as consts :
public const CurDoc as string = "CURRENT_DOCUMENT"

From what I know about const, every call to CurDoc will be replaced with the
text "CURRENT_DOCUMENT" during compilation. Is this right? If yes then
wouldn't it be better to declare it as:
public shared readonly CurDoc as string = "CURRENT_DOCUMENT"

This way there'll be a reference to this string, instead of it being copied
at each access point. What's the best practice for these?
Thanks
Amit
 
From what I know about const, every call to CurDoc will be replaced with the
text "CURRENT_DOCUMENT" during compilation. Is this right?

Sort of. There's no "calling" going on though.

This way there'll be a reference to this string, instead of it being copied
at each access point. What's the best practice for these?

That's what you'll get when using a const too, without the need for a
field access.



Mattias
 
Amit,
In addition to the other comments:

The important distinction between Const & Readonly is when the field is
defined in another assembly.

For example:

' Project 1
public Const ConstDoc as string = "CURRENT_DOCUMENT"
public Shared Readonly ReadOnlyDoc as string = "CURRENT_DOCUMENT"

' Project 2
' references Project 1

When you use ConstDoc in Project 2, a copy of the literal is placed in
Project 2 assembly, if you recompile Project 1 without recompiling Project
2. Project 2 will continue to use the original value of ConstDoc.

Where as when you use ReadOnlyDoc in Project 2, Project 2 will ask Project 1
for the value at runtime, allowing you to freely recompile Project 1 without
recompiling Project 2.

Also Const will be evaluated (known) at compile time, where as Readonly can
be computed at run time.

Another important difference is that Const are implicitly Shared, where as
Readonly can be either a Shared or instance field. For example
EventArgs.Empty is an example of a Shared Readonly field, I will use Shared
instance fields for fields that are not known until I construct the object,
however I want to ensure the value of the field never changes...

Hope this helps
Jay
 
Back
Top