Google News
logo
C# - Interview Questions
What is the difference between constant and readonly in C#?
A const keyword in C# is used to declare a constant field throughout the program. That means once a variable has been declared const, its value cannot be changed throughout the program. 
 
In C#, a constant is a number, string, null reference, or boolean values. 
 
For example :
class IB {
 
   // Constant fields
   public const int xvar = 20;
   public const string str = "InterviewBit";
 
   // Main method
   static public void Main()
   {
 
       // Display the value of Constant fields
       Console.WriteLine("The value of xvar: {0}", xvar);
       Console.WriteLine("The value of str: {0}", str);
   }
}

Output :

The value of xvar is 20.
The value of string is Interview Bit
On the other hand, with readonly keyword, you can assign the variable only when it is declared or in a constructor of the same class in which it is declared. 
 
Example :
public readonly int xvar1;
   public readonly int yvar2;
 
   // Values of the readonly 
   // variables are assigned
   // Using constructor
   public IB(int b, int c)
   {
 
       xvar1 = b;
       yvar2 = c;
       Console.WriteLine("The value of xvar1 {0}, "+
                       "and yvar2 {1}", xvar1, yvar2);
   }
 
   // Main method
   static public void Main()
   {
     IB obj1 = new IB(50, 60);
   }
}

Output :
The value of xvar1 is 50, and yvar2 is 60
 
* Constants are static by default while readonly should have a value assigned when the constructor is declared. 
* Constants can be declared within functions while readonly modifiers can be used with reference types.
Advertisement