Kiril Stanoev
Kiril Stanoev

Reputation: 1865

Using an attribute to throw an exception in .NET

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

Answers (3)

Fredy Treboux
Fredy Treboux

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

Vilx-
Vilx-

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

Noldorin
Noldorin

Reputation: 147340

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.

Upvotes: 5

Related Questions