Adam has a groovy post on T4, but he’s under the impression that you can’t use C# extension methods in T4. I just wanted to discuss the limitations that exist and show how you can take advantage of this cool C#/VB 3.5 feature.
Extension methods require you to declare a top-level static class, and don’t support nested class scope.
With T4, it’s necessary to create a class feature block <#+ #> if you want to declare another class directly in your template and class feature blocks translate this into a nested class.
This means you can’t use the really obvious syntax of
BTW, note that I’ve set language=”C#v3.5″ in my template directive to switch T4 to use the latest compiler.
However, to get things to work, we need to move our WoogaHelper class into a separate assembly and import that into T4; then all is sunny and happy in the world.
In a library assembly building to produce ExtMethods.dll:
Then add a reference to the ExtMethods assembly (either as an assembly or project reference) to the project that contains your T4 template and add an assembly and import directive to your template, like so:
Extension methods can be particularly helpful within T4, as you often want to do some obscure code spit based on a type that would make no sense given an item of that type in any other context. Enjoy.