5.3 Getters And Setters

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

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

public class Date
{
    private int month = 7;

    public int Month
    {
//      reads value
        get
        {
            return month;
        }
//      inserts correct value
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}
  1. The get accessor reads the month

  2. The set accessor can write when the value is greater than 0 and less than 13.

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

  1. Employee Id cannot be negative.

  2. Employee Name cannot be null.

Getters and Setters are great ways to gain even more control over your application. You can read more about getters, setters, and properties in general here.

Next: Exception Handling

Last updated