I'm developing a class library with C#, .NET Framework 4.7.1 and Visual Studio 2017 version 15.6.3.
I have this code:
public static T Add<T, K>(T x, K y)
{
dynamic dx = x, dy = y;
return dx + dy;
}
If I use with this code:
genotype[index] = (T)_random.Next(1, Add<T, int>(_maxGeneValue, 1));
genotype
is a T[]
.
I get the error:
Argument 2: cannot convert from 'T' to 'int'
But if I change the code:
public static K Add<T, K>(T x, K y)
{
dynamic dx = x, dy = y;
return dx + dy;
}
I get the error:
CS0030 Cannot convert type 'int' to 'T'
When I get this error T
is a byte
.
How can I fix this error? Or maybe I can change random.Next
to avoid doing the Add
.
The minimal code:
public class MyClass<T>
{
private T[] genotype;
private T _maxGeneValue;
public void MinimalCode()
{
Random _random = new Random();
genotype = new T[] {0, 0, 0};
int index = 0;
_maxGeneValue = 9;
genotype[index] = (T)_random.Next(1, Add<T, int>(_maxGeneValue, 1));
}
}
It is a generic class because the genotype
array can be of bytes or integers or floats. And I use the random to generate random values between 1 and _maxGeneValue
. I need to add one because the maxValue
in Random is exclusive.
The elements in the genotype
array could any of the built-in types, as far as I know numerics. And I don't want to create a class for each of the types I'm going to use (and use the biggest one in array declaration, i.e. long[]
, is a waste of space).