Understanding constants
There are some scenarios in which we do not want to change the value of a variable after it is initialized. Examples can include mathematical constants (pi, Euler's number, and so on), physical constants (Avogadro's number, the Boltzmann constant, and so on), or any application-specific constants (the maximum allowed number of logins, the maximum number of retries for a failed operation, status codes, and many others). C# provides us with constant variables for this purpose. Once defined, the value of a constant variable cannot be changed during its scope. If you try to change the value of a constant variable after it is initialized, the compiler will throw an error.
To make a variable constant, we need to prefix it with the const
keyword. The constant variables must be initialized at the time of declaration. Here is an example of an integer constant initialized with the value 42
:
const int a = 42;
It is important to note that only the built-in types can be used to declare constants. User-defined types cannot be used for this purpose.