Practical Difference Between Constant And Readonly In C#

Constant(const) Readonly
Constants are immutable values and do not change their value for the life of the program.

Constants are known as the compile time.
ReadOnly is also an immutable value and does not change its value for the life of the program.

ReadOnly is known as the runtime.
Assigned a value at the time of declaration.

Ex
  1. public const int number = 0;  
 
 
 
 
 
Assigned a value either at the run time or inside a constructor (instance initialization).

Ex
  1. class Program {  
  2.     public readonly int number = 10;  
  3.     public Program() {  
  4.         number = 20;  
  5.     }  
  6. }  
Constant cannot be static i.e. you cannot declare constant as static.

Ex
  1. public static const int number = 10;  
It will throw an error at the compile time.
Readonly can be static i.e. you can declare readonly as static.

Ex
  1. public static readonly int number = 10;  
It will not give an error.
Constant value can access with the class name.

Ex
  1. class Program {  
  2.     public  
  3.     const int number = 10;  
  4.     static void Main() {  
  5.         Console.Write(Program.number);  
  6.     }  
  7. }  
Readonly value can access by instance of the class.

Ex
  1. class Program {  
  2.     public readonly int number = 10;  
  3.     static void Main() {  
  4.         Program p = new Program();  
  5.         Console.Write(p.number);  
  6.     }  
  7. }