Constant VS ReadOnly In C#

Dictionary Meaning:

The meaning of “Constant” is “Something that does not or cannot change or vary.”

What is Constant?

Constants are unchangeable value that do not change for the life of the program. Constants are declared with the const modifier.



Let’s have a look at Const:

Constants are immutable values which are known at compile time and do not change for the life of the program. Value must be initialized,initialization must be at compile time.

This type of constant is called Compile time Constant.

For example:

  1. namespace ConstReadonly  
  2. {  
  3.     class Program  
  4.     {  
  5.         public const int month = 12;  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Console.WriteLine(month);  
  9.             Console.ReadKey();  
  10.         }  
  11.     }  
  12. }  
Notes:
  1. To assign value to const is must, otherwise it’ll get compilation error (A const field requires a value to be provided).

  2. By default it is static, if we set it static it’ll get compilation error (Cannot be marked static).

  3. Value is hard coded.

  4. Can define const only on primitive types like int, double, etc.

Let’s have a look at Read-only:

Read-only variables can only being assigned on its declaration and another way is to assign value inside an instance/static constructor.

This type of constant is called Run time Constant.

For example:

  1. namespace ConstReadonly  
  2. {  
  3.     class Program  
  4.     {  
  5.         public static readonly int week = 7;  
  6.         public const int month = 12;  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine(week);  
  10.             Console.ReadKey();  
  11.         }  
  12.     }  
  13. }  
Another example:
  1. namespace ConstReadonly  
  2. {  
  3.     class ReadOnly  
  4.     {  
  5.         public readonly int week = 7; // initialized at the time of declaration  
  6.         public ReadOnly()  
  7.         {  
  8.             week = 10;  
  9.         }  
  10.     }  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             ReadOnly objRn = new ReadOnly(); // initialized at run time  
  16.             Console.WriteLine(objRn.week);  
  17.             Console.ReadLine();  
  18.         }  
  19.     }  
  20. }  
Notes:
  1. To assign value is not mandatory, but once it is assigned that do not change for the life of the program.

  2. They can be static or instance.

  3. Must have set instance value.

  4. Value can be assigned at run-time. If we set the value directly it'll get a compilation error, A static read-only field cannot be assigned to (except in a static constructor or a variable initializer).

Up Next
    Ebook Download
    View all
    Learn
    View all