Executing custom code on attributed classes at compile time
Eoghan Murray read my blog on custom attributes and sent the following question:
I am interested in doing the following: Adding an attribute to certain classes, so that, at Compile time, information about them gets written to an xml file. I see that the built in System.ObsoleteAttribute can raise warnings at compile time, so I want to do something similar, except execute a piece of my own code at compile time.
Now that I've spelled it out, it seems impossible!
Now that I've spelled it out, it seems impossible!
It is an interesting question. I don't think it is possible to execute the code at compile time. If anyone knows how, please explain.
What you can do is build a custom attribute and mark your classes with it. Then, have a post-build step that executes a program against the compiled assemblies that uses reflection to find the classes marked with your attribute and execute whatever code you want.
For example, you create a custom attribute called DocumentThis. You mark all of your classes with that attribute, then create a small Documentor program that reflects over a .NET assembly and writes the name of each class that has the DocumentThis attribute to a text file. Then your post-build step for the project can call Documentor with the project's output as the target.
That's the best I can think of, let me know how it works.