Wednesday, March 11, 2009

Extension Method to Get Custom Attributes with Reflection

I was working on my parameter validation with PostSharp proof of concept and I needed an easy way to get a list of custom attributes of a specific type from objects in the System.Reflection namespace like MethodInfo or ParameterInfo.

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) 
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);

return attrs;
The usage is pretty cut and dry, but you can reference the afore mentioned article: Validate Parameters Using Attributes and PostSharp

No comments:

Post a Comment