Does anyone know if it's possible to extend the AttributeUsage attribute? I'm worried it's all hardcoded in the compiler without any way for us to mess around in there.
Right now, I can use the AttributeUsageAttribute to specify the target on which my custom attribute will be applied, but I'm limited to the AttributeTargets enum. I can't build more complex rules, like "This attribute can only be applied to a class deriving
from MarshalByRefObject", or "Only applies to a method with a return value". I can implement these checks at run-time with reflection, but I'd rather get as many compile-time warnings as possible.
I was hoping that this was extensible - that I can inherit AttributeUsageAttribute, override the "validate target" method and insert my own custom logic there and let the compiler handle it. However, the class is sealed and doesn't even have any such method
- the logic is hiding somewhere else. I'm assuming the compiler loads and runs the code for the AttributeUsageAttribute at compile-time, rather than there being a sneaky shortcut involved.
Naturally, I'm aware of the danger of having the compiler execute unvalidated code at compile-time. I'm still hoping for some method of achieving this.
Any ideas?
-
-
Attributes get compiled down to metadata, not program code.
If the compiler would actually execute any code you wrote this would be a huge security hole.
So in your case you can just write your own attribute and a custom verifier that gets called after the compiler (if you are using MS build this shouldn't be a problem)
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.