Finding all classes with a particular attribute
Solution 1:
IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
where TAttribute: System.Attribute
{ return from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where t.IsDefined(typeof(TAttribute),inherit)
select t;
}
Solution 2:
Mark posted a good answer, but here is a linq free version if you prefer it:
public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
{
var output = new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var assembly_types = assembly.GetTypes();
foreach (var type in assembly_types)
{
if (type.IsDefined(typeof(TAttribute), inherit))
output.Add(type);
}
}
return output;
}