The readonly Member

Like the constant member, (declared with the const keyword) the readonly member is used to represent an unchanging value. But, whereas the value assigned to the constant must be written in the source code, as demonstrated in the following line

const decimal MassOfElectron = 9.0E-28m;

the value of the readonly member does not have to be known until the program is running. The value of a readonly member is initialized in a constructor and cannot be altered after that moment. So, while the constant member remains unchanged throughout the lifetime of a compiled program, the readonly member merely stays unchanged during the lifetime of an object.

Syntax Box 13.4 shows how a readonly member is declared. Apart from the readonly ...

Get C# Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.