C# constants best practice

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:

const readonly
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.

Use const:

  1. To construct enumerated values.
  2. To construct attributes.
  3. 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).
  4. 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.

Use readonly:

  1. When you need to assign the value with an output of a function.
  2. When you need to assign the value in the constructor.
  3. 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.
  4. 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.
  • http://wisentechnologies.com/it-courses/.net-training.aspx .Net Training in Chennai

    readonly modifier cannot be specified for properties.