In C# there are two way to define constants, using const and readonly. Some may say that there is the enum keyword, but it’s actually a group of const. In case you don’t know, there are some important differences between these two keywords:
|It is always a static class member.||It can be a static or instance class member.|
|The value is evaluated at compile time. Therefore, the only
possible values for constants of reference types are string and null.
|The value is evaluated at run time and embedded to every assembly that uses it. Therefore, the values for
readonly fields can be the output of method calls.
|It has to be initialized at the declaration.||It can be initialized at the declaration or the class constructor.|
|It can be used to construct enumerated values.||It cannot be used to construct enumerated values.|
|It can be used to construct attributes.||It cannot be used to construct attributes.|
Based on the differences, we can establish a practice when to use const and readonly.
- To construct enumerated values.
- To construct attributes.
- When you are sure that the value will never change between releases, for example, mathematical constants (pi, Euler’s number, golden ratio, and so on).
- When declared inside a class with internal modifier. The internal modifier ensures the fields cannot be used in another assembly, thus eliminating versioning issues when the value is changed.
- When you need to assign the value with an output of a function.
- When you need to assign the value in the constructor.
- When the fields are going to be used by other assemblies. This prevents the value from being embedded to the assembly, hence there will be no issues even if the value of the fields are changed.
- When declared inside a class with public modifier. The public modifier indicates that the class is available to be used by other assemblies, hence there can be a versioning issue if const is used instead of readonly.