PropertyInfo - GetProperties with attributes

I am trying to create a custom attribute check for webform projects.

I can already get all the properties from my class, but now I don’t know how to filter them, and just get properties that have some attribute.

For example:

PropertyInfo[] fields = myClass.GetType().GetProperties(); 

This will return all the properties to me. But how can I just return the properties using an attribute of type testAttribute, for example?

I have already searched for this, but after several attempts to solve this problem, I decided to ask here.

+8
c # system.reflection
source share
4 answers
 fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0) 

See the documentation for GetCustomAttributes() .

+9
source share

Use Attribute.IsDefined :

 PropertyInfo[] fields = myClass.GetType().GetProperties() .Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false)) .ToArray(); 
+23
source share

you can use

  .Any() 

and simplify the expression

  fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any()) 
+2
source share

You probably need the GetCustomAttributes memberInfo method. If you are looking specifically for, say, TestAttribute, you can use:

 foreach (var propInfo in fields) { if (propInfo.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0) { // Do some stuff... } } 

Or, if you just need to get them all:

 var testAttributes = fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0); 
+1
source share

All Articles