views:

90

answers:

3

Hello, 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

+5  A: 

You're looking for an AOP (Aspect Oriented Programming) library, which can do this quite easily. I would recommend giving PostSharp a try. The example on the home page should give an indication how you might use it on a property/method.

Noldorin
+1  A: 

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".

Vilx-
+1  A: 

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.

Fredy Treboux