Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a value to a C# generic?

Tags:

c#

.net

generics

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.

like image 628
paulot Avatar asked Aug 20 '13 00:08

paulot


People also ask

How do you pass a value to another variable?

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.

How do you pass a value?

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.

Can you pass-by-reference in C?

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.

How are arguments passed in C?

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.


2 Answers

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

like image 196
Daniel A. White Avatar answered Oct 08 '22 05:10

Daniel A. White


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.

like image 44
Reed Copsey Avatar answered Oct 08 '22 05:10

Reed Copsey