How to get a list of properties with a given attribute?

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.

7 Answers
7

Leave a Comment