Different between constants and read-only variables?
Loading
Different between constants and read-only variables?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sachin SinghPosted Sep 25, 2022, 5:38 PM
1 Kilometer=1000 meters, can you change it? No, this is universal contant.
Pie= 3.14, can you change it? Yes, you can take n numbers after decimal (3.142567). This is partial constant.
So, whenever you are dealing with universal constant that will never ever change, you use const.
when you need some values to change but only at runtime ,you use readonly, you set the value at configuration and read it inside the class constructor.
for resourses that may not need to change per request we use readonly+static for example DbContext or connectionstring
Rajanikant HawaldarPosted Sep 25, 2022, 3:23 PM
While constants and read-only variable share many similarities, there are some important differences:
- Constants are evaluated at the compile-time, while the read-only variables are evaluated at the runtime.
- Constants support only value-type variables, while read-only variables can hold reference type variables.
- Constants should be used when the value is not changing during the runtime, and read-only variables are used mostly when their actual value is unknown before the runtime.
Muhammad Imran AnsariPosted Sep 25, 2022, 12:37 PM
A constant field is a compile-time constant, the readonly field can be used for run time constants. constant fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
Further you can read the following good article on the differences:
https://www.c-sharpcorner.com/blogs/difference-between-constant-and-readonly