#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: #700 – Using a set Accessor To Enforce Casing « 2,000 Things You Should Know About C#

  2. Pingback: #701 – Centralize Business Rules Logic in set Accessors « 2,000 Things You Should Know About C#

  3. I would caution against throwing exceptions in property setters. The programmer who writes to the property isn’t normally expecting a run-time exception. Perhaps Code Contracts are a better solution here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: