I've been curious whether it's possible to get a list of all the classes with my own attribute without explicitly iterating over all types defined in an assembly. The thing I've tried is to make attribute's constructor write all the types into a static field. For unknown reason the list of the types doesn't contain a single entry. The following code outputs 0
to the console window. Why?
[AttributeUsage(AttributeTargets.Class)]
class SmartAttribute : Attribute {
public static List<Type> Types = new List<Type>();
public SmartAttribute(Type type) {
Types.Add(type);
}
}
[SmartAttribute(typeof(Test))]
class Test {
}
class Program {
static void Main(string[] args) {
Console.WriteLine(SmartAttribute.Types.Count());
foreach (var type in SmartAttribute.Types) {
Console.WriteLine(type.Name);
}
}
}