Are the const and readonly keywords in C# similar?

const and readonly keywords might seem to be alike; they both are used to modify attributes and properties in a class and are immutable values. So what are const and readonly modifiers and what are their differences?

What is a const?

Constants are immutable values and modifiers; they contain a value that can not be changed after initialization.

An example of a const declaration:

const double PI = 3.14;
What is a readonly?

Readonly modifiers are also immutable values; they contain a value that can not be changed after construction and for the rest of program life.

An example of a readonly declaration:

readonly string name = "Joe";
What is the difference between const and readonly?

Constants need to be initialized when used or declared. Thus they are known at compile time and will not change after that.

\\ below will result in an error
const double PI;

\\ below is correct
const double PI = 3.14;

Readonly keyword on the other hand does not necessary need to be initiliazed when declared. They can be initialized in a constructor. Thus they are known at runtime and will not change after that.

\\ both statements below are correct
readonly string name;
readonly string name = "Joe";
2.Change in Constructor

Since readonly field value does not have to be initialized when declared, they can be changed inside a constructor. A const value can not on the other hand.

private readonly string color = "Black";

public Vehicle(string color) {
  this.color= color;
3.Value Assignment

A readonly value can be assigned a value based on a calculation. Whereas a const value can not.

\\ below statements are valid
readonly double a = Math.Cos(90);
readonly double b = 7.2;

\\ below statement is invalid and raises an error
const double a = Math.Cos(90);

\\ below statement is valid
const double b = 1;
4.Accessing variables

Constant variables have to be accessed using the class name only. On the other hand readonly variables have to be acccessed using the instance of the class.

An example is below:

\\ usage of const variable
double pi = Math.PI;

\\ usage of readonly variable
Vehicle car = new Vehicle();
string color = car.Color;
Show Comments