correct usage of static and const

  • Thread starter Thread starter Sek
  • Start date Start date
S

Sek

hi folks,

i have a bunch of strings used in my code in many places.
these strings reside inside a instantiable class.

so, i want to replace these with constant/static variable to control
the occurences.

i have been looking at both static and const variables as the options,
but couldn't decide on one.

share your view towards the problem.

TIA
sek
 
For my perference, if I'm likely to change the string in my code, it'll
declare it as static. If I won't, I'll declare it as const.
 
again, is it more appropriate to use "static readonly" instead of
"static" to replace "const"?
 
Yes you should use readonly ... otherwise you are saying the variable can be
changed?

As for const vs static readonly, like everything in computer science ... it
depends. Both have some pros and cons. Consts are evaluated at compile time
where as static readonlys are evaluated at runtime.

If this is a library that is referenced by other apps etc (which is the case
90% of the time) then I would use static readonly as opposed to const. If
you use const here you would have to recompile your library and everything
that referenced your library (static readonly you would only have to
recompile your library)

Annoyingly static readonly cannot be used in a switch.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
Thanks greg.
Thanks lau.

I understand, the choice is more based on the system.
From the performance perspective, won't const win over the
static(readonly) as they need to resolve the symbol during runtime
unlike the const?
 
Hi Sek,
I understand, the choice is more based on the system.
static(readonly) as they need to resolve the symbol during runtime
unlike the const?
No, there is no difference of code while runtime. After jit-compiling the
code is exactly the same.

For every variable wich is accissible from other asseblies it should use
const only if it is really const.
I mean, the value would never ever change. E.g. mathematical constants like
pi, e .....
If it's private or internal it's more a matter of taste resp. coding-style.
 
Back
Top