O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required