hi..
what is the difference between const and readonly variables?
please explain.
Loading
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.
Sam HobbsPosted Sep 25, 2011, 12:11 PM
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.
VulpesPosted Sep 25, 2011, 6:28 AM
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.