What is the difference between CONST and READONLY?

Both are meant for constant values. 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.

readonly int b;
public X()
{
    b = 1;
}
public X(string s)
{
    b = 5;
}
public X(string s, int i)
{
    b = i;
}

Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example:

public static readonly uint l1 = (uint) DateTime.Now.Ticks;

(this can’t be possible with const)

Tagged , . Bookmark the permalink.

Leave a Reply