Hello!

Tell me, please, how can I pass into the template not only the type, but also a specific value, for example, an integer? For example, there is such code:

public class Sample <T, size> { private T[] arr = new T[size]; // =( ... } 

How to pass a number through size?

Thank!

    3 answers 3

    Perhaps you need such an idea. Declare an attribute whose property contains the number you need, and mark this class with the attribute that you will substitute as a Generic parameter. And in the static constructor of the Generic class, read the attribute for T.

    • This is certainly a solution to the set (contrived) task, but if I saw a similar implementation in the project, I would consider it a crutch and throw it out. - wind

    What for? This is not possible in the CLR. Pass the size to the class constructor.

    • This is possible in C ++, and it is very convenient! For example, I would like to immediately indicate the dimension of the array in the class, without using initialization in the constructor. It's comfortable. - Salivan 5:41 pm
    • Use typed lists instead of arrays. - wind
    • 2
      @Asen In c ++ it is not so much done for convenience as for all sorts of chips and patterned magic. In Sharpe is simply impossible. And about the convenience of a controversial issue. Anyway, you have to specify the size, either in the constructor or when parameterizing the template. - IronVbif
    • Is it impossible in sharpe? This is news ... sorry = ( - Salivan
    • 2
      @Asen - Due to the lack of typedef'ов beauty of records like Sample<MyType, 26> and Sample<MyType, 136> looks rather doubtful. - Apparently, the question arose from an academic, rather than practical interest, since in real life such use of generics is rather pointless. - Costantino Rupert

    Indeed, why? In Sharpe, this is more than stupid ... The meaning of a generic is to generalize, not to concretize. If the size of the array is known in advance, use a static field, a constant. If you need to create dynamically - the designer is in your hands (including the static designer). I do not know how in the pros, but in Sharp it is just more than illogical ...