Omu
Omu

Reputation: 71198

check if PropertyDescriptor has attribute

I'm trying to check if a property has the DataMemberAttribute applied (using TypeDescriptor)

this is what I have now:

PropertyDescriptor targetProp = targetProps[i];

var has = argetProp.Attributes.Contains(
Attribute.GetCustomAttribute(typeof(DataMemberAttribute).Assembly,typeof(DataMemberAttribute)));

the problem is that

Attribute.GetCustomAttribute(typeof(DataMemberAttribute).Assembly,typeof(DataMemberAttribute))

returns null

Upvotes: 13

Views: 8040

Answers (3)

D.L.MAN
D.L.MAN

Reputation: 1093

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!

Upvotes: 1

Thomas
Thomas

Reputation: 2137

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));

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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();

Upvotes: 32

Related Questions