const vs readonly in C#

July 30, 2019

You must have used the keywords const & readonly in C# but do you know the actual difference between the two?
Let’s understand what are they & what is the difference among them.

Const

Syntax:
const int x = 5;
A variable declared a const means that it is a constant & its value cannot be changed at runtime. Once the value is assigned, it can never be altered.
The compiler needs to resolve the constant values during the compilation& hence, it is necessary to assign some value to const variables.
For example:
const int x; 
// is an invalid statement as we didn’t assign any value to xconst int x = 5; 
// is a valid statement
Also, const variables are implicitly static by nature.
For example:
public class ClassA {
    public const int val = 10;
}
We can use ClassA.val notation to access val without initializing the ClassA instance.

Readonly

Syntax:
readonly int x = 5;
A variable declared readonly means that its value will become readonly once initialized & cannot be altered after that with the difference that the compiler need not resolve the readonly values at runtime.
Instead, the readonly values can be initialized until the class constructor exits. In other words, we can initialize the readonly variables inside the constructor & once the control moves out of the constructor, their value will be freezed & cannot be altered.

The subtle difference between const & readonly

Besides the differences compared above, there is a subtle difference among the two.
Consider the following class ClassA in AssemblyA
public class ClassA 
{
 public const int ConstVal = 5;
 public readonly int ReadOnlyVal; public ClassA() 
 {
  readOnlyVal = 10;
 }
}
Consider there is another assembly AssemblyB that references AssemblyA
When AssemblyB is compiled, ConstVal of class ClassA will be translated into the Intermediate Language (IL) & its value (i.e. 5) will be saved in the compiled AssemblyB code. Thus, if in future, I decide to change the value of ConstVal from 5 to 10, then I have to build both the assemblies again.
Where as, the readonly variable ReadOnlyVal is stored as a ref (memory location) to the variable & if I decide to change the value of ReadOnlyVal in future from 10 to 20, I do not need to rebuild both of the assemblies. Instead, I will build only the AssemblyA containing ClassA & the changed value will be picked up by the AssemblyB’s reference to that readonly variable.

You Might Also Like

0 comments

Follow by Email