Reputation: 1865
Is it possible to use some kind of attribute to throw an exception. This is what I mean. Instead of doing this:
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
NotifyPropertyChanged("Age");
if (value < 18)
{
throw new Exception("age < 18");
}
}
}
Do something like this:
[Range(18,100, ErrorMessage="Must be older than 18")]
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
NotifyPropertyChanged("Age");
}
}
Any help would be greatly appreciated!
Best Regards, Kiril
Upvotes: 0
Views: 1027
Reputation: 3331
As the accepted solution says, it's impossible to do this directly but can be achived by using a tool like PostSharp. Just to add to what's already been told, I wouldn't recommend throwing from a property, or doing validation of this sort on assignment as generally it doesn't hold too much value and can be the cause of some trouble. It may depend on the scenario though.
Upvotes: 1
Reputation: 106920
No, that's not possible. You will have to do the validation yourself in the setter - just like NotifyPropertyChanged.
Btw - this is called "Aspect Oriented Programming".
Upvotes: 1