Beginner's question

R

R.A.M.

When to use "readonly" and when to use "const"?
Could you explain me please?
Thank you very much!
/RAM/
 
S

Sericinus hunter

R.A.M. said:
When to use "readonly" and when to use "const"?
Could you explain me please?
Thank you very much!

'const' is evaluated at compile time, while 'readonly' -- at runtime.
The former is more efficient, but may have implications. If you
have an assembly which declares some public 'const' members and another
assembly which references it and uses that members, the second assembly
will have that values 'imprinted'. Which means that if you ever need
to change the value in the referenced assembly, you will need
to recompile and redistribute the referencing assembly too.

One more difference is that 'const' is also 'static' by definition.

Also, if your variable is not of primitive type (numeric or string)
you have no choice, only 'readonly' can be used.

I would say, in more cases than not 'readonly' is a better choice
since it guarantees correctness.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

The MSDN for const is very especific about this:

Note The readonly keyword is different from the const keyword. A const
field can only be initialized at the declaration of the field. A readonly
field can be initialized either at the declaration or in a constructor.
Therefore, readonly fields can have different values depending on the
constructor used. Also, while a const field is a compile-time constant, the
readonly field can be used for runtime constants as in the following
example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;
 
G

Guest

Functionally, the difference is that a const must be and can only be assigned
on the line it is declared. A readonly variable can be assigned either on
the declaration line or in a constructor. I've also read (but haven't
verified) that consts are handled more efficiently.

Generally I would say prefer a const over a readonly variable unless the
value is only known at executin time.
 

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

Similar Threads

beginner's question: const vs readonly 3
?? Basic C# Language Questions ?? 14
newbie question 6
const and readonly 5
C# graphics for the beginner 1
Excel Filter Listview userform VBA 0
const or readonly 3
Readonly locals? 8

Top