It is not possible to add T with K because it returns T (or common to numeric)

I am 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 this code:

genotype[index] = (T)_random.Next(1, Add<T, int>(_maxGeneValue, 1));

genotypeis T[].

I get an error message:

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 an error message:

CS0030 Unable to convert type 'int' to 'T'

When I get this error T, this byte.

How can I fix this error? Or maybe I can change random.Nextto avoid execution Add.

Minimum 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));
    }
}

, genotype . 1 _maxGeneValue. , maxValue Random .

genotype , , . , ( , .. long[], ).

+4
1

T - ,

. , . 3, .

, : , , , , - ; dynamic .

- . 3 : byte, int float. , , :

  • "" ( "" , ).
  • float, .

, :

public byte Add(byte left, byte right) { .... }
public int Add(int left, int right) { .... }
public float Add(float left, float right) { .... }

- : ? int? : 250 + byte 10 return? A byte int? a int, . int s. , .

+6

Source: https://habr.com/ru/post/1695237/


All Articles