How to get a list of properties with a given attribute?
The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.First() as MyAttribute};
As far as I know, there isn't any better way in terms of working with Reflection library in a smarter way. However, you could use LINQ to make the code a bit nicer:
var props = from p in t.GetProperties()
let attrs = p.GetCustomAttributes(typeof(MyAttribute), true)
where attrs.Length != 0 select p;
// Do something with the properties in 'props'
I believe this helps you to structure the code in a more readable fashion.
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]()
.