#250 – Using a set Accessor to Convert or Validate Property Data

We can use a property’s set accessor to do some validation on the new property value.  We may want to force the data to be within a particular range, do some conversion on the data, or throw an exception if an invalid value is specified.

Here’s an example where we use the set accessor of the Dog.Age property to enforce the constraint that a dog’s age can’t be less than 0.1.

        private float age;
        public float Age
        {
            get
            {
                return age;
            }
            set
            {
                // Enforce minimum age of 0.1
                age = (value < 0.1f) ? 0.1f : value;
            }
        }

Here’s another example, where we throw an exception if the user tries to set Name to an empty string.

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value == "")
                    throw new Exception("Name can't be empty!");
                else
                    name = value;
            }
        }
Advertisements