Read-Only Fields

Read-only fields can be initialized only from inside the constructor or through a field initializer. Basically, this stimulates the use of immutability as it protects against further modification of the field after the containing object’s (or type’s) initialization. The following code illustrates correct use of a read-only field that’s initialized within a constructor:

image

Figure 11.5 shows a violation against the read-only field assignment requirements. As you will see later, the use of auto-implemented properties does not (sadly) provide for the use of read-only fields.

Figure 11.5. Read-only fields should not be initialized after ...

Get C# 4.0 Unleashed 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.