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.

class ElevenFiftyEmployee
{
        //Fields
        private int _id;      //ID can't be negative
        private int _yearsExperience;  //An employee has some experience.
        private string _jobTitle;
        private string _employeeName; //Name can't be null
        private string _commonWorkQuote;
        private string _company;

        //Dealing with the Id problem. Without the getter and setter, it can be negative.

        public int Id
        {
            set
            {
                if (value < 0)
                    throw new Exception("The Employee Id is not valid");
                this._id = value;
            }
            get
            {
                return this._id;
            }
        }


        //Dealing with the Id problem. Without the getter and setter, it can be negative.

        public string Name
        {
            set
            {
                try
                {
                    this._employeeName = value;
                }
                catch (Exception)
                {

                    if (string.IsNullOrEmpty(value))
                        throw new Exception("The Employee name is not valid");
                }

            }
            get
            {
                return this._employeeName;
            }
        }



        public void SetCommonWorkQuote(string quote)
        {
            this._commonWorkQuote = quote;
        }

        public string GetQuote()
        {
            return this._commonWorkQuote;
        }

        //Use this if you don't have conditions to deal with.
        public string CommonWorkQuote { get; set; }
        public string CompanyName { get; set; }
    }
}
  1. Employee Id cannot be negative.

  2. Employee Name cannot be null.

class Program
    {
        static void Main(string[] args)
        {
            ElevenFiftyEmployee paul = new ElevenFiftyEmployee();
            paul.Id = 10;
            paul.Name = "Paul";
            paul.CommonWorkQuote = "Somebody's got a case of the Mondays.";
            paul.CompanyName = "Eleven Fifty";

            Console.WriteLine("{0} {1} {2}", paul.Id, paul.Name, paul.CompanyName);
            Console.ReadLine();
        }
    }

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