views:

47

answers:

3

I am looking for a method to add custom keywords to the .net framework that offer "special" pre-complier benefits or are ignored by the compiler.

Example I would like to do something like this

public static factory class Foo<T>
{
     public static create T Create();
}

I would like to add a pre-compile event that translates that code into functioning C#. I have already considered a few options (which I can not post here because I am limited to 1 hyperlink) none of them do exactly what I am looking to do. Does anyone else have any suggestions?

+1  A: 

This can't be done with the current C# version, unless you are willing to:

  • Create your own C# compiler
  • Create your own preprocessor to run before the actual compiler.
driis
/agree, you may be able to get close with templating - suggest looking into T4 engine perhaps.
James Kolpack
you mention "reprocessor to run before the actual compiler" I can not find any way to do this where I preserve the original cs file. The preprocessor event was my first thought. If you have an article or suggestion on how I can modify the cs file only for the compiler and not the original file that would be perfect.Thank you for your answer
George
+1  A: 

I suggest something more like this:

[Factory()]
public static class Foo<T>
{
    [Create()]
    public static T Create();
}

You can build your own attributes and should be able to use them to accomplish what you need here.

Joel Coehoorn
This is a good suggestion but requires implementation. The big thing I was trying to allow for is the decorator patter via deligation.Example if you have an interface that has 40 methods but you only want to change one method, using a custom keyword i could fill in all the other method implementations. I am currently doing something like this in the code now with attributes but it requires the class be abstract then I emit the code at runtime to extend to the class. I then have a factory to get the extended version.I would rather just handle it all at compile time if possible.
George
A: 

Could you get away with just using annotations? Your example suggests you might, but I realize it could be misleading.

Hank Gay
Annotations work well in my existing implementation but require a large price at startup of the application where I use codedom to create a new assembly at startup. I may move to a postsharper like model and just modify the IL but that will still not give me the compile time support I would like when it comes to code sense.thank you for you suggestion
George