Constant vs Readonly

Difference between a Constant and Readonly?

Both constant and readonly belong to the category of constant values with only major difference that one is a compile time constant and other is a runtime constant.

Compile time constant

"Constant" is a compile time constant type i.e. when you declare it you have to assign it a value otherwise you will not be able to compile your program.

In the following screen shot you will notice that readonly field is alright even if you do not assign it a value but constant field requires a value otherwise you will not be able to compile your program.


Run time constant

"Readonly" is a run time constant type i.e. when you declare it you do not have to assign it a value but you can only assign it a value inside the class constructor otherwise you will get a compile time error. If you want to define it on compile time that is totally alright as well.




So in order to properly define it look at the image below:

Remember once it is defined in the constructor you can not change it anywhere else.

Conclusion

  • 1# - Constant and Readonly fields are very frequently used in the programming but how they are used really makes a difference. End result for both of them is the same once value is set you can not change it. However; readonly fields have an exception case you can change the readonly value define at the class level inside the constructor. we will see this in a snapshot shortly.
  • 2# - Constant must have a value defined at the compile time you will not be able to assign it a value later; not even in the constructor or any other place. we will see this in a snapshot shortly.
  • 3# - Readonly can either be defined at compile time or runtime but will only accept a value inside the constructor if not defined during compile time. Once defined you can not change the value outside the constructor.
  • 4# - public constants defined in a class can not be accessed out side the class using a instance of the class. However you should be able to access them using the class name directly. we will see this in a snapshot shortly.



Properly defined program with all conditions satisfied will look like:


Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)