const
is static and is solved at compile time. That is, what will be put in the code that consumes the constant is the value established in it. If by chance it changes its value, it has to compile everything that consumed it to have the new value. In addition the value has to be constant as well, that is, it has to be able to be completely solved during the compilation. So you can’t use it for much.
A good example is PI
.
A bad example for its use is MaxThreads
. One day you may want to change and may have problems. In this case it is best to use:
public static readonly int MaxTreads = 4;
I put in the Github for future reference.
readonly
can be applied to static or instance fields (there is proposal to have locally). It is not quite a constant, just indicates that after initializing its value can no longer be changed. It is immutable, but not constant, even though he’s usually considered that way. The values used in it can be solved at runtime because its initialization occurs only at that moment, either at the time you need to use static data or at the time of creating an instance depending on the context it is declared.
As the data is initialized at runtime, even if its value can be solved at compile time is not done, so the consumer code of these "constants" are sure that they will always take the current value of the code that created it.
If you need to initialize at runtime you have no option, you can only use readonly
. If you need the "constant" to be instance, you should also use readonly
.
The basic rule when you choose is that you need a piece of data that you can change in the future, use readonly
. If it is universally constant - it will never change - you can use const
.