Constant vs Readonly in C#
Difference Between Const and ReadOnly.
One of the most important concepts that we commonly use while writing a C# code . Still there are many developers who do not exactly understand the basic difference between these two and in which case we should go for any of them. Today in this blog I will explain the uses and the difference between them in the most simplest way.
Const and Readonly both of them are the constants both are used to declare the constant values in our programs as shown below.
Now We will be talking about the difference between the two.
Const is a compile time constant i.e it is processed at the compile time only by the compiler.
Once we set the value of a const field then it is not allowed to change it again.
Once we make any fiend as const we need to assign the value like shown above val1=1000, we cannot leave val1 without assigning any value.
ReadOnly is the Runtime Constant i.e it is processed at Runtime only.
Readonly constant are not forced to assign the value at the compile time.
We can assign value to the readonly fields using the constructor or any config file. As shown below
In the above Image we can see that Val2 can be assigned or manipulated using the constructor.
So, The time when you are sure about the value that is it going to the same for entire program in any case use CONST, But if there might be a chance that a value could be changed in any scenerio go for ReadOnly.This is all you need to know about the Const and ReadOnly.
Hope Now you have a better clarity for both the concepts.