I have a type, t
, and I would like to get a list of the public properties that have the attribute MyAttribute
. The attribute is marked with AllowMultiple = false
, like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
Currently what I have is this, but I'm thinking there is a better way:
foreach (PropertyInfo prop in t.GetProperties())
{
object[] attributes = prop.GetCustomAttributes(typeof(MyAttribute), true);
if (attributes.Length == 1)
{
//Property with my custom attribute
}
}
How can I improve this? My apologies if this is a duplicate, there are a ton of reflection threads out there...seems like it's quite a hot topic.
This avoids having to materialize any attribute instances (i.e. it is cheaper than
GetCustomAttribute[s]()
.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:
I believe this helps you to structure the code in a more readable fashion.
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.
There's always LINQ:
If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:
which you can use like
typeof(Foo).HasAttribute<BarAttribute>();
Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:
In addition to previous answers: it's better to use method
Any()
instead of check length of the collection:The example at dotnetfiddle: https://dotnetfiddle.net/96mKep