Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if PropertyDescriptor has attribute

Tags:

c#

.net

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

like image 784
Omu Avatar asked Jun 29 '12 10:06

Omu


Video Answer


2 Answers

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();
like image 96
Darin Dimitrov Avatar answered Sep 22 '22 05:09

Darin Dimitrov


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!

like image 43
D.L.MAN Avatar answered Sep 22 '22 05:09

D.L.MAN