PropertyInfo - GetProperties with attributes

Gui picture Gui · May 10, 2011 · Viewed 13.3k times · Source

I'm trying to create a custom attribute validation for a webform projects.

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

For example:

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

This will return me all the properties. But how can i just return the properties using a attribute like "testAttribute", for example?

I've already searched about this but after a few time trying to solve this i decided to ask here.

Answer

Kirk Woll picture Kirk Woll · May 10, 2011

Use Attribute.IsDefined:

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