Is metaprogramming possible in C#?

Brian R. Bondy picture Brian R. Bondy · Oct 26, 2008 · Viewed 26.1k times · Source

In particular, would it be possible to have code similar to this c++ code executed at compile time in c#?

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Answer

Jacob Krall picture Jacob Krall · Oct 26, 2008

No, metaprogramming of this complexity is not supported directly by the C# language. However, like @littlegeek said, the Text Template Transformation Toolkit included with Visual Studio will allow you to achieve code generation of any complexity.