ludo
ludo

Reputation: 1466

How to pass a value to a C# generic?

In C++ templates have the feature that you can pass a value as the argument to the template of a function. How can I do the same in C#?

For instance, I want to do something similar to the following:

template <unsigned n> struct Factorial {
     enum { 
        result = n * Factorial<n - 1>::result;
     };
};
template <> struct Factorial<0> {
      enum {
        result = 1;
      };
};

but in C#. How can I do this?

By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example.

Upvotes: 8

Views: 5171

Answers (3)

Jan D&#246;rrenhaus
Jan D&#246;rrenhaus

Reputation: 6717

You are trying to make the compiler do stuff that your code should do at runtime.

Yes, this is possible in C++. In C#, It is not. The equivalent of your code in C# would be:

public class Factorial
{
    public static ulong Compute(ulong n)
    {
        if (n == 0)
            return 1;
        return n * Factorial.Compute(n - 1);
    }
}

Note that, while static code is already a bad violation of the OOP principle (but sometimes necessary), using value-based templates is even worse. Your types should depend on other types, which is possible using generics. They should not depend on concrete values.

Upvotes: -2

Reed Copsey
Reed Copsey

Reputation: 564323

but in C#. How can I do this?

By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example.

As Daniel explained, this is not possible via generics.

One potential alternative is to use T4 Templates. Depending on your needs, you could potentially generate your classes based off the templates at compile time, which sounds like it might meet your needs.

Upvotes: 5

Daniel A. White
Daniel A. White

Reputation: 190897

C# generics are not like C++ templates in that way. They only work with types and not values.

Upvotes: 6

Related Questions