Search code examples
c#variadic-templates

Simulate variadic templates in C#


Is there a well-known way for simulating the variadic template feature in C#?

For instance, I'd like to write a method that takes a lambda with an arbitrary set of parameters. Here is in pseudo code what I'd like to have:

void MyMethod<T1,T2,...,TReturn>(Fun<T1,T2, ..., TReturn> f)
{

}

Solution

  • C# generics are not the same as C++ templates. C++ templates are expanded compiletime and can be used recursively with variadic template arguments. The C++ template expansion is actually Turing Complete, so there is no theoretically limit to what can be done in templates.

    C# generics are compiled directly, with an empty "placeholder" for the type that will be used at runtime.

    To accept a lambda taking any number of arguments you would either have to generate a lot of overloads (through a code generator) or accept a LambdaExpression.