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
- public const int number = 0;
|
Assigned a value either at the run time or inside a constructor (instance initialization). Ex
- class Program {
- public readonly int number = 10;
- public Program() {
- number = 20;
- }
- }
|
Constant cannot be static i.e. you cannot declare constant as static.
Ex
- 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
- public static readonly int number = 10;
It will not give an error. |
Constant value can access with the class name.
Ex
- class Program {
- public
- const int number = 10;
- static void Main() {
- Console.Write(Program.number);
- }
- }
|
Readonly value can access by instance of the class.
Ex
- class Program {
- public readonly int number = 10;
- static void Main() {
- Program p = new Program();
- Console.Write(p.number);
- }
- }
|