Constants and Read-only in C#

Constants and Read-only is a very common question in all C# interviews but many people get confused by it. I know the reason why this happens, it's because we never use constants and Read only together in our applications specially Read only.

Now what happens is we get confused with Read only because Constants is a fully self explanatory but Read only is not fully self explanatory.

To fully understand the Constants and Read only we just need to see three scenarios.

After that you will never ever forget Constants and Read only.

  1. First thing about constants and Read only is how they are declared. Main difference comes here only.

Whenever we declare constant with keyword const we must initialize it at the same time otherwise it will throw error. See Below.

code

Here it is working fine but below when it is declared but not initialized it throws an error. See below.
code
Now see the Read only. Now that rule does not apply to Read only. You can only declare or declare as well as initialize at the same time.
code

Here it is only declared and not initialized. Now see below where it is declared as well as initialized.

code

So the first difference is Constant should be declared as well as initialized but Read only can be declared only or declared as well as initialized at the same time.

Now once the value of constant is declared and initialized it will not change throughout the application. So Constant is relatively easy to understand.

Let’s deal with Read only now. We will see the main difference first.

The main difference is you can assign value to Read only on 2 occasions. First when the variable is declared and second inside the class constructer.
code

Now the last thing which comes into our mind is what if no value is assigned to a Read only variable.
We it will take a default value like 0 for int and null for string.

Next Recommended Reading Look at C# constants