READONLY and CONST are nearly same but they are different in few places. You can see the differences between these keywords while declaring or assigning access modifiers to them. In this article we will discuss few of these differences between them.
While writing code we use readonly and const keywords and get confused while using them. In this article I will try to explain few differences between them.
Let's see the differences between readonly and const keyword.
|Constant variables must be assigned a value at the time of declaration (compile-time). You cannot assign value to constant variable anywhere except at the time of declaration.||A readonly variable can be initialized either at the time of declaration or within the constructor of same class.|
|Use const keyword to declare a Constant variable.||Use readonly keyword to declare a Readonly variable.|
|Constant variables are implicitly static.||By default readonly it is not static.|
|A constant field is a compile-time constant.||Readonly fields are compile-time as well as run-time constants.|
const float pi = 3.14;
readonly string name = 'rahul';
|You should use constant, if you are confident that the value of the constant will not change.||If you think value can change at run time, you can use readonly.|
|You cannot change constant value due to its static nature.||YYou can also make a readonly variable as static which will start acting as constant variable.|
Hope this article was helpful. Please like, rate this article and please don't forget to comment as your comments are very useful for us and it helps us improving the level of articles. You can also contact us with your queries.