I noticed that objects which take custom attributes implement ICustomAttributeProvider. There is a GetCustomAttributes(Type, Boolean) overload which will get the custom attributes of a specific type, but I like the generic syntax better. I also prefer to return an IList rather than an array, but I don't really have any reasons for or against this preference.
I wrote a generic extension method for anything that is an ICustomAttributeProvider that will return a strongly typed list of attributes on the object:
public static List<T> GetAttributes<T>(this ICustomAttributeProvider pi)The usage is pretty cut and dry, but you can reference the afore mentioned article: Validate Parameters Using Attributes and PostSharp
where T : Attribute
List<T> attrs = new List<T>();
foreach (object a in pi.GetCustomAttributes(typeof(T), false))
if (a is T) attrs.Add(a as T);