Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating additional code through a custom attribute

I am still fairly new to C# and I have a question regarding attributes. Is it possible to write a custom attribute which generates additional code at compile time. For example:

[Forever]
public void MyMethod()
{
    // Code
}

Turns into:

public void MyMethod()
{
    while (true)
    {
        // Code
    }
}
like image 377
Dave Avatar asked May 20 '11 00:05

Dave


2 Answers

Out of the box, no, this isn't something that can be done. Using PostSharp though, this can be achieved:

http://www.sharpcrafters.com/aop.net/compiletime-weaving

like image 159
BFree Avatar answered Oct 23 '22 21:10

BFree


Afterthought works similar to PostSharp by performing compile-time modifications to your assemblies. In the case of Afterthought you can choose how to identify the changes to make, either by looking for attributes you have defined, looking for common patterns, or simply establishing conventions.

For example, I am working on an example using Afterthought to automatically implement Entity Framework interfaces at compile-time for types exposed by a DbContext in a compiled assembly. In this case I am simply looking for any type that is a subclass of DbContext and then looking at the properties on this type to determine which POCO types to modify to work with Entity Framework.

However, compile-time manipulation of assemblies like this, while powerful, is still for me a choice of last resort. It is not natively supported by the .NET framework and Microsoft tools. Though I wrote Afterthought to support complex cases where this level of indirection was required, I prefer to use standard object-oriented patterns and intrinsic C# language features like delegates as much as possible. Ultimately, introducing custom attributes that inject code introduces a domain specific language into your solution, which will be one or thing to learn/understand for someone reviewing your code, like when answering an SO question ;-)

like image 33
Jamie Thomas Avatar answered Oct 23 '22 19:10

Jamie Thomas