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:

class Person{    private static int s_population;    private readonly int _id;    public Person()    {        _id= s_population++;    }    public int ID    {        get { return _id; }    }}

Figure 11.5 shows a violation against the read-only field assignment requirements. As you will see later, the use of auto-implemented properties ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.