We know that C# supports const and readonly variables and generally uses them interchangeably, but we also should notice that they offer different behaviors. Always remember, const is compile time and readonly is runtime. This will always help in choosing the correct one according to the situation.

Let’s look into the behavior of both of these in detail:

const (Compile time constant)

const are “compile time constants”. Compile time constants are a bit faster than run time constants. When performance is the highest criteria and we are sure that value of constant will not change for different release, use const.

For example, if we define and use a const, as below,

  1. const int meterInKm = 1000;
  2. int distance = 10;
  3. int totalMeter = distance * meterInKm;

it will be converted to below after compilation:

  1. const int meterInKm = 1000;
  2. int distance = 10;
  3. int totalMeter = distance * 1000;

For example, if you try below, you will get a compile time error: (** Using REPL to show compile time error. Look at end of the article on how to open REPL)

C#

Readonly (Run time constant)

readonly defines “run time constants”. Run time constants are a bit slower but are more flexible than compile time constants. The main difference between these are that they are resolved at run time, which means whenever we use a readonly variable it is referenced while when we use const the value is used.

For example, if we define and use a readonly, as below:

  1. readonly int meterInKm = 1000;
  2. int distance = 10;
  3. int totalMeter = distance * meterInKm;

it will be converted to below after compilation:

  1. const int meterInKm = 1000;
  2. int distance = 10;
  3. int totalMeter = distance * meterInKm;

** Notice the difference between const and readonly.

Open REPL

REPL - Read–Eval–Print Loop, provides an interactive shell inside visual studio where user can do a quick programming and do experiment.

Below describes how to open C# REPL,

C#

This will open the below window where you can write and experiment with your codebase,

C#