1
Answer

Generics and assigning variables

Photo of Carl

Carl

17y
2.2k
1
I try to define a generic function in c# that is capable of manipulating an array of integers, or an array of bools, depending on the parameter given to the function.

Is this possible?

E.g. I have the following code, this will result in a compile error.

void fill_array<T>(int count, ref T[] array_out) {

for (int i= 0; ii < count; count++) {
if (typeof(T) == typeof(int)) array_out[i] = i % 2; else array_out[i] = (i % 2) == 1;
// results in cannot cast int to T, and cannot cast bool to T.
}

return;
}

Answers (1)