Check if a property has a specific attribute?

c#

Solution

You can try the following code the check against an attribute value of a property:

public bool CheckPropertyAttribute(Type type, string property, 
                            Type attributeType, string attProp, object value)
{
    var prop = type.GetProperty(property);
    if (prop == null) return false;
    return CheckPropertyAttribute(prop, attributeType, attProp, value);
}
public bool CheckPropertyAttribute(PropertyInfo prop, Type attributeType,
                                   string attProp, object value){
   var att = prop.GetCustomAttributes(attributeType, true);
   if (att == null||!att.Any()) return false;
   var attProperty = attributeType.GetProperty(attProp);
   if (attProperty == null) return false;
   return object.Equals(attProperty.GetValue(att[0], null),value);
}

Usage::

if(CheckPropertyAttribute(pi, typeof(DisplayAttribute), "AutoGenerateField", false)){
  //...
}

NOTE: I provided 2 overloads, but in your case I think you just need to use the second overload (the case in which we already have some `PropertyInfo`).

Problem

I'm using WCF RIA services to do a few small pieces of a web application; mainly populate/filter lists (I don't understand RIA well enough yet to trust I'm doing server side validation correct). One of the things I do is get a list of which fields have which generic type, by which I mean, strings are a text type, decimal, double, integer are numeric, etc. I do that with a LINQ query ``` Fields = type.GetProperties().Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null && pi.Name != "DisplayName") .Select(pi => new FieldData { FieldName = CommonResources.AddSpacesToSentence(pi.Name, true), FieldType = "Text" })..... ``` The field `DisplayName` is a special field that should be ignored in lists, but as this application is growing I realize this isn't a very maintainable/expandable/buzzwordable way to go about this. What I really want is to know is if metadata for the `DisplayName` property has the attribute `[Display(AutoGenerateField = false)]` Is there a way I can check for that in my LINQ? Update: After posting this I was able to slowly work out how to do this (I've never worked with Attributes in this way before). The answer given by King King looks nice and is very generic, but the way I wound up solving this was different, so if you're interested in another way, here's what I found. I added this to the LINQ query: ``` ((DisplayAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayAttribute))).GetAutoGenerateField() == false ```

Original source