check if PropertyDescriptor has attribute

You could use LINQ. A chain of the .OfType<T>() and .Any() extension methods would do the job just fine:

PropertyDescriptor targetProp = targetProps[i];
bool hasDataMember = targetProp.Attributes.OfType<DataMemberAttribute>().Any();

There are 3 ways:

  • First:

    PropertyDescriptor targetProp = targetProps[i];
    bool hasDataMember = targetProp.Attributes.Contains(new DataMemberAttribute());
    
  • Second:

    PropertyDescriptor targetProp = targetProps[i];
    bool hasDataMember = targetProp.Attributes.OfType<DataMemberAttribute>().Any();
    
  • Third:

    PropertyDescriptor targetProp = targetProps[i];
    bool hasDataMember = targetProp.Attributes.Matches(new DataMemberAttribute());
    

Best Regard!


Found a much nicer answer in there: https://stackoverflow.com/a/2051116/605586

Basically you can just use:

bool hasDataMember = Attribute.IsDefined(property, typeof(DataMemberAttribute));

Tags:

C#

.Net