Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
In the context of C#, a constant is a type of field or local variable whose value is set at compile time and can never be changed at run time. It is similar to a variable by having a name, a value, and a memory location. However, it differs from the variable by its characteristic of getting initialized only once in the application. A constant is declared using the keyword "const".
Variables of built-in type, excluding System.Object whose non-changing value is known at compile time, can be declared as constants. During compilation, the constant value is substituted for its literal value into the intermediate language code by the compiler. This results in better integrity of the application by reducing accidental bugs. Usage of constants also improves performance over regular variables. It improves code readability and provides better maintenance, since it is easier to update the constant value in a single place before recompilation of software.
A constant has the following characteristics or must adhere to the following rules:
Some of the best practices while using constants include:
A constant differs from the readonly variable in that the former needs to be initialized during declaration time and is static, while the latter can be initialized during declaration or any one time (like in a constructor so as to have different values based on the constructor type). Hence, a constant is called a compile-time constant, and a readonly variable is a runtime constant.