13

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

Omu
  • 69,856
  • 92
  • 277
  • 407
  • Probably your assembly has no DataMemberAttribute applied. You can't even apply a DataMemberAttribute to an assembly, only properties and fields are allowed. – Fox32 Jun 29 '12 at 10:24

3 Answers3

31

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();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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));
Community
  • 1
  • 1
Thomas
  • 2,127
  • 1
  • 32
  • 45
1

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!

D.L.MAN
  • 990
  • 12
  • 18