There are some tools, like PostSharp
, that generates code when compiling.
How is it done? Can anyone provide some simple example?
There are some tools, like PostSharp
, that generates code when compiling.
How is it done? Can anyone provide some simple example?
PostSharp is an IL-rewriter. It loads the assembly that's generated by the .NET compiler and modifies the generated IL. Calling this 'generating code' is only technically accurate, it certainly isn't the kind of code that, say, a C# compiler can compile.
Doing this yourself isn't exactly trivial, you have to have black-belt skills in understanding IL. Getting it wrong can produce very hard to diagnose problems. I think there are some open source projects that use the IL rewriting technique, like Spring.NET, they ought to be a good starting point for getting this right. I do see excellent hits when googling "IL rewriter". Do expect to burn a considerable amount of time on it. It is also a high-maintenance item, a new release of .NET often breaks the rewriter.