Thursday, December 18, 2008

The Difference between "const" and "readonly" in C#

It has been baffling me for a while since I've used the two keywords for pretty much the same purposes, but after reading a little of the documentation, the difference between the two became much more clear (emphasis mine):

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;