Pat Newell
Pat Newell

Reputation: 2294

Test for Attributes From Within the Code of Other Attributes

Is it possible to test for the existence of an attribute within the code of another attribute?

Say you have the following class definition:

public class Inception {
    [Required]
    [MyTest]
    public int Levels { get; set; }
}
public class MyTestAttribute : ValidationAttribute {
    public override bool IsValid(object o){
        // return whether the property on which this attribute
        // is applied also has the RequiredAttribute
    }
}

... is it possible for MyTestAttribute.IsValid to determine whether Inception.Levels has the RequiredAttribute?

Upvotes: 6

Views: 99

Answers (1)

Anders Abel
Anders Abel

Reputation: 69310

In the specific case of a ValidationAttribute it is possible, but you have to use the other IsValid overload that has a context parameter. The context can be used to get the containing type and also get the name of the property that the attribute is applied to.

protected override ValidationResult IsValid(object value, 
  ValidationContext validationContext)
{
  var requiredAttribute = validationContext.ObjectType
    .GetPropery(validationContext.MemberName)
    .GetCustomAttributes(true).OfType<RequiredAttribute>().SingleOrDefault();
}

Upvotes: 3

Related Questions