2.4.8 How to Define Readonly Fields

Readonly fields are used when a field will only hold a single value and should never be changed.

For example, the Booth class has a public TicketPrice field. This field can be assigned from anywhere meaning if a Guest at the Zoo had access to the Booth they could make the TicketPrice 0 if they wanted to.

To start we can make the field private so that only the Booth class can change the value.

There's still an issue, however. Say we have a method that changes the ticket price. This is a method that the attendant of the booth could have access to.

But we don't anyone messing with the ticket price. We want it to be $15.00 and not be able to be changed. To do this we need to make the field readonly and give it a value.

Now the ChangeTicketPrice method doesn't work because the ticketPrice field cannot be assigned to.

However, we can still access the value of the field normally.