When, if ever, should we use const?

Frederick The Fool picture Frederick The Fool · Feb 17, 2009 · Viewed 12.6k times · Source

Const is baked into the client code. Readonly isn't. But const is faster. May be only slightly though.

The question is, is there ever any scenario where you should prefer const over readonly? Or to rephrase, are we not practically always better off using a readonly instead of a const (keeping in mind the above-said baking thing)?

Answer

Andrew Arnott picture Andrew Arnott · Feb 17, 2009

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.