samedi 30 mai 2020

C# Generic method for random number generation

I see that there is a similar question for C++. Does anyone know why this method works when the method is non-generic, but as soon as I make it generic, the random number portion of code fails? Error: Cannot implicitly convert type int to 'T'. If I can't use generics, I will have to rewrite the same function over and over for each different length of array.

public void fillGenericArray<T>(T[] inputArray) where T : IComparable
        {
            var randomNumb1 = new Random();


            for (int i = 0; i < inputArray.Length - 1; i++)
            {
                Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
                Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
                // oneHundredArray.Size++;
                Console.WriteLine($"{Size}");
            }
        }



Aucun commentaire:

Enregistrer un commentaire