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.
- Compile time constants
- As const are processed at compile time itself, they are replaced with their values as soon as code is compiled.
For example, if we define and use a const, as below,
- const int meterInKm = 1000;
- int distance = 10;
- int totalMeter = distance * meterInKm;
it will be converted to below after compilation:
- const int meterInKm = 1000;
- int distance = 10;
- int totalMeter = distance * 1000;
- Limited to numbers (int, long, double….) and strings
- We cannot use any other datatype as const.
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)
![]()
- Should be assigned when declared, if not assigned it will throw compile time error as below:






Viknaraj ManogararajahPosted Jul 21, 2018, 11:03 PM
Nice Article, Thank you for sharing