Reputation: 71198
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
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
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
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