Gui
Gui

Reputation: 9803

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.

Upvotes: 8

Views: 14930

Answers (4)

syned
syned

Reputation: 2321

You can use

    .Any()

and simplify expression

    fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())

Upvotes: 3

Kirk Woll
Kirk Woll

Reputation: 77546

Use Attribute.IsDefined:

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

Upvotes: 24

verdesmarald
verdesmarald

Reputation: 11866

You probably want the GetCustomAttributes method of MemberInfo. 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);

Upvotes: 1

svick
svick

Reputation: 244757

fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0)

See documentation for GetCustomAttributes().

Upvotes: 10

Related Questions