SHASHANGKA SHEKHAR'S BLOG

Hi, I am Shashangka Shekhar, Working with Microsoft Technologies. This is my personal blog where I share some of my experiences.

Constant VS Read-Only

Dictionary Meaning:

The meaning of “Constant” is “Something that does not or cannot change or vary.”

What is Constant?

Constants are unchangeable value that do not change for the life of the program. Constants are declared with the const modifier.

constrn

Let’s have a look at Const:

Constants are immutable values which are known at compile time and do not change for the life of the program. Value must be initialized,initialization must be at compile time.

This type of constant is called Compile time Constant.

For example:

Notes:

  1. To assign value to const is must, otherwise it’ll get compilation error (A const field requires a value to be provided)
  2. By default it is static, if we set it static it’ll get compilation error (Cannot be marked static)
  3. Value is hard coded.
  4. Can define constonly on primitive types like int, double, etc.

Let’s have a look at Read-only:

Read-only variables can only being assigned on its declaration and another way is to assign value inside an instance/static constructor.

This type of constant is called Run time Constant.

For example:

Another example:

Notes:

  1. To assign value is not mandatory, but once it is assigned that do not change for the life of the program
  2. They can be static or instance.
  3. Must have set instance value.
  4. Value can assign at run-time. If we set it value directly it’ll get compilation error (A static read-only field cannot be assigned to (except in a static constructor or a variable initializer)

Post a comment