Wednesday, February 3, 2010

GetProperties(BindingFlags.DeclaredOnly) returns no properties

If you're trying to use reflection to retrieve a list of properties and you want only the properties declared in a given type but not the inherited ones, msdn says you need to call GetProperty passing down the DeclaredOnly binding flag.

What msdn doesn't say is that if you just pass down DeclaredOnly you'll get nothing back (and if you ended up on this post through a google search that's probably the reason why).

In order to get back the properties you're looking for you need to pass down also the Public and Instance binding flags - smt like this should work:
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
This is probably working "as designed" but could definitely make you waste a bit of time (as it did for me).

In the spirit of human hive intelligence - hope it helps some other average Joe out there.



5 comments:

un empathique said...

thank you ! this helps me a lot ^^

Anonymous said...

THANKS! I'm not sure how/why this is by design but your post helped me figure my issue out.

Anonymous said...

Thanks a lot. Your post helped me to resolve my issue and save a lot of time.

Anonymous said...

Nice one, thanks very much for this you solved me problem for me with a mere 1 minute's Googling.

Van Fanel said...

Thank you VERY MUCH !