Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Sep 25, 2022, 1:38 PM EDT
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.
public class Class1 { private const int meterToKM=1000; private readonly double_pi; public Class1() { _pi= ConfigurationManager.Appsettings["pi"]; } public void Method1() { // use the variables } }for resourses that may not need to change per request we use readonly+static for example DbContext or connectionstring
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Sep 25, 2022, 8:37 AM EDT
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
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Sep 25, 2022, 11:23 AM EDT
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.