Readonly and const variable in C#

Background

Whenever I took the interview of any candidate then I always asked one question to them what is readonly and constant variable then believe me even four plus experienced candidate get confused, so whatever I learned from my tech gurus about this concept  according to that I will try to explain it in details so beginners and experienced candidate can understand it.

So let us start with definition

 
What is Constant variable ?

The variable whose value can not be changed during the execution of the program is called as constant variable.

In the above definition value can not be changed during execution of the program means we can not be assign the values to constant variable at run time it must be assign at compile time at the declaration of constant variable.
 
Constants are of following types
 
 
 
In the above diagram ,we can see the Constants are of two types
  1. Compile time constants (const)
  2. Runtime constants  (Readonly)
  •  Compile time constants

The compile time constants are declared by using the const keyword which value can not be changed during the execution of the program.

Syntax
 
     int const a=10;
Some key points about const variable
  •   Its must to assign value at the time of declaration.
             eg.
             int const a=10;  
  •   const only allow constant variables into the expression.
   eg.
          int const a=10;
          int const b=20; // correct
          int const c=a+b; 
 
          int  d=1;
          int const c=d+b;   //compile time error because d variable is the non constant into expression.
 
  •   const can be declared at class level as wel as inside the method.
  •  const can not be declared using static keyword because they are by default static.
  •   constants are  absolute constant which value can no be changed or assigned at the run time.
  • constant variable are compile time constant variable.
When to use const
 
The const is used when their is value is absolute constant such PI values which can not be changed,but according to your requirement you can use it as wish as rather than PI values declaration.
 
Example of const   variable.
  1. using System;  
  2.   
  3. namespace UsingConst  
  4. {  
  5.     class Program  
  6.     {  
  7.         const int a = 10;  
  8.            
  9.        static void Main(string[] args)  
  10.         {  
  11.             const int b = 20;  
  12.             const int c = b + a;  
  13.             Console.WriteLine(c);  
  14.             Console.ReadLine();  
  15.         }  
  16.     }  

The output of the above program is 30,from the above example we clearly see that the const must be assign the value at declaration time and in expression both the variable must be const.
 
Runtime constants (Readonly)

The Run time constants are declared by using the Readonly keyword which value can not be changed during the execution of the program.

Syntax
int Readonly a; or
 int Readonly a=0;
Some key points about const variable
  •  Its not  must to assign value at the time of declaration,we can also assign the value for readonly through constructor.
eg.
int readonly a;
a=0;
  •   Readonly allows, readonly  constant as wel as non  readonly constant  variables into the expression.
eg.
int readonly a=10;
int b=1;
int readonly c=a+b;
  • Readonly can be declared only at class level not inside the method.
  • Readonly can not be declared using static keyword because they are by default static.
  • Readonly   constants  value can  be set through reference variable.
  • Readonly  constant variable are runtime time constant variable.
When to use Readonly
 
We can use Readonly,   when value is not  absolute constant  means which can be changed frequently,like dollar vs INR ,in this requirement we can set the value through configuration file or another variable expression so we can avoid to change class file frequently.
 
Example of Readonly variable.
 
let us define the value from config file  for readonly constant variable ,which will be set through constructor .
  1. <configuration>  
  2.   <appSettings>   
  3.     <add key="DollarPrice" value="61.23"/>  
  4.   </appSettings>  
  5.     
  6. </configuration> 
Now, let us explain it through sample program
  1. using System;  
  2. using System.Configuration;  
  3.   
  4. namespace Usingreadonly
  5. {  
  6.     class Program  
  7.     {  
  8.         readonly int a = 10;  
  9.         int b = 30;  
  10.         int c;  
  11.         readonly string r;  
  12.         public Program()  
  13.         {  
  14.             r = ConfigurationManager.AppSettings["DollarPrice"];  
  15.             Console.WriteLine("The dollar value is:"+" "+r);  
  16.             Console.WriteLine();  
  17.             c = a + b;  
  18.             Console.WriteLine("The addition of readonly constant and non Readonly constant is :"+Environment.NewLine+ c);  
  19.             Console.ReadLine();  
  20.         }  
  21.   
  22.         static void Main(string[] args)  
  23.         {  
  24.             Program p = new Program();  
  25.              
  26.             Console.ReadLine();  
  27.         }  
  28.     }  

In the above program ,we have assigned the value for readonly constant through constructor which is defined in the config  file,because readonly constant not must to assign the value at the time of declaration.
Now run the program the output will be as.
 
 
 
Let us  outline the differences  between const and readonly variables.
  1. const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  2. const variables can declared in methods ,while readonly fields cannot be declared in methods.
  3. const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  4. const field is a compile-time constant, the readonly field can be used for run time constants.

Summary

I hope this article is useful for interview prospective if you have any suggestion regarding this article then please contact me.

Up Next
    Ebook Download
    View all
    Learn
    View all