Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4 reference a const in a static class at compile time

I have a T4 C# file in which I need to reference a constant in a static class. The static class is in the same namespace.

Is this possible?

The below is merely an illustration. I need to calculate the actual constant based on existing constants, but there is also a call to an extension method involved. To keep it simple, I am merely illustrating the concept.

.cs file:

namespace me
{
  public static class Stat
  {
    public const int Const = 1;
  }
}

. tt file:

...
namespace me
{
  public static int Test
  {
    return <#= Stat.Const #>;
  }
}
like image 561
IamIC Avatar asked Oct 04 '22 19:10

IamIC


1 Answers

It is indeed possible. However you need to do a couple things first:

  1. Ensure your class and const are both public (which they are).
  2. Build your solution to generate a dll (which will contain the static class and const you want to reference).
  3. Reference the current assembly in your .tt with <#@ assembly name="$(TargetPath)" #>
  4. Reference the namespace in which your static class is found with <#@ import namespace="ns" #>
  5. Generate your .tt.
  6. Rebuild your solution to include the newly-generated code in the assembly.

That should do it. The tricky bit is in realising that your .tt doesn't work like any old class file in your project. Because it is generated it needs something to generate from, which in this case is your project dll that you have to generate beforehand.


And as promised, here is the blog post I wrote about this question :)

like image 155
Levi Botelho Avatar answered Oct 07 '22 03:10

Levi Botelho