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.
In order to pass a value using call by reference, the address of the arguments are passed onto the formal parameters. It is then accepted inside the function body inside the parameter list using special variables called pointers.
Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value. In Pass by value, parameters passed as an arguments create its own copy.
Pass by reference Even though C always uses 'pass by value', it is possible simulate passing by reference by using dereferenced pointers as arguments in the function definition, and passing in the 'address of' operator & on the variables when calling the function.
By default, LotusScript® passes arguments to functions and subs by reference. If the argument is an array, a user-defined data type variable, or an object reference variable, you must pass it by reference. In most other cases, you use the ByVal keyword to pass variables by value.
C# generics are not like C++ templates in that way. They only work with types and not values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With