What are constants?
Constants are immutable values whose values are known at runtime and cannot be changed in the whole lifetime of a program.
Features of constants
- Only C# primitive can be declared as const. Shown below is how a constant is declared.
- User-defined Types such as class, struct and arrays cannot be declared as const.
A constant can only be initialized when it is declared and cannot be changed.
-
- class A {
- public
- const int month = 12;
- }
-
- class B {
- public
- const int month;
- public B() {
- this.month = 12;
- }
- }
When the compiler encounters a constant identifier in C# code, it substitutes the literal value directly into the IL code that produces it because there is no variable address associated with the constant at runtime.