hi..
what is the difference between const and readonly variables?
please explain.
Const and readonly
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
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 attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Sep 25, 2011, 2:28 AM EDT
1. Const can be applied to fields or local variables; readonly can only be applied to fields.
2. When applied to a field, const is implicitly static (i.e. it applies to all instances); readonly can be either instance or static.
3. Const values can only be set where the constant is defined; readonly values can be set either where the field is defined or from within a constructor.
4. The C# compiler must be able to fully compute the value of a const at compile time because the constant will actually be replaced by that value. This means that constants are limited to those fundamental types which support literals, such as int, double, decimal, bool, char and string.
In contrast the value of a readonly field need not be computed until runtime, which is the reason why a static readonly field is sometimes preferred to a const field.
Sam HobbsRank #108 · 20.5K reputationPosted Sep 25, 2011, 8:11 AM EDT
A simplified explanation of the difference is that the value of a const is determined at compile time whereas the value of a readonly item is determined during execution.