5.3 Getters And Setters
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
GetSet
Discussion
Accessors are the second half of the syntax used when writing a property. It looks like this { get; set; }
. Accessors are used to show that the private fields can be read, written, or manipulated. The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write.
Properties have many uses: 1. Can validate data before allowing a change 2. Can show data on a class where that data is actually stored from another source (database) 3. Can take action when data is changed such as changing the value of other fields
Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get-accessor and/or a set accessor. For example:
The get accessor reads the month
The set accessor can write when the value is greater than 0 and less than 13.
Can you see how this can be useful? We will need restrictions on some of our properties in the future.
Another example using Getters and Setters would be mimicking inputting data for Eleven Fifty employees. Check this out, then we'll talk about it.
Employee Id cannot be negative.
Employee Name cannot be null.
Last updated