Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyInfo - GetProperties with attributes

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.

like image 789
Gui Avatar asked May 09 '11 22:05

Gui


1 Answers

Use Attribute.IsDefined:

PropertyInfo[] fields = myClass.GetType().GetProperties()
    .Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false))
    .ToArray();
like image 189
Kirk Woll Avatar answered Oct 19 '22 04:10

Kirk Woll