Difference between readonly and const in C#
Recently I was asked what the difference was between **readonly **and **const **in C#, and I couldn’t really tell the exact difference. There are several good articles about this, like this StackOverflow article. In this article, I’ll stick to the very basics.
On MSDN, this difference between the two is explained in a note:
The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;
Both act similary in that they cannot be changed in the “regular flow” of the application. If you want to change the value of a const or readonly in the midst of an object’s lifetime, you’ll get build errors. There is one certain moment in the lifetime of an object where the main difference between readonly and const becomes clear. Whereas a const can never be changed in runtime, a readonly field can be set during an object’s construction. The example below should make this clear:
- A field marked as const must be initialized at declaration time.
- A field marked as readonly can be initialized on the constructor.