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!
 
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.

1 Comment

  • MarshallByRef.

    Also look at DI/AOP. These allow for code to be execute before/after/around a method/class decorated with the attribute or even configured in the appropriate file.

    w://

Comments have been disabled for this content.