A bunch of cool attributes were introduced in .NET 3.5 SP1 to help with property validation. They are in the System.ComponentModel.DataAnnotations namespace and can be used like this:
public class Person
{
[Range(0, 120)]
public int Age { get; set; }
}
Technologies like Dynamic Data, MVC, and Silverlight automatically use the attributes to enforce validation.
However, the code above still allows the following to run without throwing an exception:
Employee emp = new Employee();
emp.Age = -23;
What I want to know is can I harness these attributes in my own application (which is not Dyn Data, MVC, or Silverlight)? I had hoped that the code above would throw a validation error when the invalid value was assigned to the Age property. Or do I need to continue using the traditional validation inside the property setter like this:
private int _age;
public int Age
{
get { return _age; }
set
{
if (value < 0 || value > 120)
{
throw new ArgumentOutOfRangeException();
}
_age = value;
}
}
Maybe there is another approach that is a best practice?