Check if PropertyDescriptor attribute has attribute

I am trying to check if the DataMemberAttribute property is 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

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

returns null

+7
source share
2 answers

You can use LINQ. A chain of .OfType<T>() and .Any() extension methods will make the job just fine:

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

Found a much more enjoyable answer: https://stackoverflow.com/a/212677/

Basically you can just use:

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

All Articles