#250 – Using a set Accessor to Convert or Validate Property Data
February 22, 2011 3 Comments
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; } }
Pingback: #700 – Using a set Accessor To Enforce Casing « 2,000 Things You Should Know About C#
Pingback: #701 – Centralize Business Rules Logic in set Accessors « 2,000 Things You Should Know About C#
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.