All About Constants

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
  1. Only C# primitive can be declared as const. Shown below is how a constant is declared.
  2. User-defined Types such as class, struct and arrays cannot be declared as const.
  3. A constant can only be initialized when it is declared and cannot be changed.
    1. // Value assigned during compile time   
    2. class A {  
    3.     public  
    4.     const int month = 12; //Legal  
    5. }  
    6. // Value assingement during runtime  
    7. class B {  
    8.     public  
    9.     const int month;  
    10.     public B() {  
    11.         this.month = 12; // illegal  
    12.     }  
    13. }  
    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.