Difference between Constant and ReadOnly Variables in C#

This is the commonly asked question by the interviewers that what is the difference between ReadOnly and Constant variables. Mostly all of us know a very basic point that both keywords are used to make value fixed. But what are the differences????

Please go through the article to understand the concept.

Table of Differences

Constant ReadOnly
Constant variables are defined at the time of declaration. They cannot be modified once defined. ReadOnly variables can be defined at declaration time or in constructor (at runtime but in a non static constructor). Once initialized cannot be modified.
Values are fixed at compile time Values are fixed at runtime
class A()
{
const int i=10;
}
class A()
{
readonly int i;
public A()
{i=10;}
}

Above are the basic differences between constant and readonly variables.

How do we know where to use constant and where we go for Readonly declaration? See this is totally depends on our requirement or the situation.

If you know the value at the declaration time that not gonna be change, you can use constant. But when the value is decided at runtime you should use readonly.

Let us take an example of PI. Its value is constant right yet can be different. Some can take its value = 3.14159265 or 3.14 or 22/7.
So here at the time of development make the variable pi readonly and let the constructor give it a value what the requirement demands. Once it is defined it will become fixed.
ReadOnly
You can see in the above code that value is given at the time of object creation.

Now take a situation that your application is related to cricket. You have a variable “over”. So 1 “over” have 6 balls, it is fixed and that you know at the time of declaration, So here in this case you can make the variable ‘over’ constant.
constant

Do you know?

A field initializer (assignment statements) cannot reference a non static field/method to a static field. See the code below
Code:
int temp = 6;
const int over = temp;

This code will give compile time error.

Modified
const int temp = 6;
const int over = temp; // it will work

You can read about field initializer in MSDN – Field Initializer