Reputation: 6632
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);
}
}
}
Upvotes: 1
Views: 577
Reputation: 12325
What you are trying to do is not possible. Attributes are meta-data, they are not instantiated at run-time, so your constructor isn't called.
If you step back and think about why, it makes sense. In order for the code you propose to work, the first thing your the run time would have to do before executing any code, is create instances of all attributes. Then you'd run into some fun scenarios like:
[AttributeB]
public class AttributeA : Attribute{}
[AttributeA]
public class AttributeB : Attribute {}
Which constructor would go first, when would it know to stop, etc? It's reasons like this why the .Net architects decided not to execute Attributes constructors.
Now, to find all the types that are decorated with your attribute, you will need to iterate through all of the types in your assembly from within your Main
method (or any other executing method):
Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => Attribute.IsDefined(t, typeof(SmartAttribute)))
See get all types in assembly with custom attribute for more discussion on retrieving types decorated with attributes.
Upvotes: 1