When, if ever, should we use const?

I typically only use const for things that I know will never ever change such as the speed of light in a vacuum.

I prefer readonly for things that could potentially change. This way I only need to recompile one dll if a change happens. An exception to this rule of thumb is if the variable is private/protected/friendly to its own assembly. In those cases it is safe to use const.


You can use a const value as a case in a switch statement, fwiw.


I believe the only time "const" is appropriate is when there is a spec that you're coding against that is more durable than the program you're writing. For instance, if you're implementing the HTTP protocol, having a const member for "GET" is appropriate because that will never change, and clients can certainly hard-code that into their compiled apps without worrying that you'll need to change the value later.

If there's any chance at all you need to change the value in future versions, don't use const.

Oh! And never assume const is faster than a readonly field unless you've measured it. There are JIT optimizations that may make it so it's actually exactly the same.


Const vs readonly:

A quick synopsis on the differences between 'const' and 'readonly' in C#: 'const':

  • Can't be static.
  • Value is evaluated at compile time.
  • Initiailized at declaration only.

'readonly':

  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in the constructor.

The above states const can't be static. That is a misnomer. They can't have the static keyword applied because they are already static.

So you use const for static items that you want evaluated at compile-time.