Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, returning an array in a function

Tags:

arrays

c#

.net

I have a method that generates an array. I want to return this array so I can use it another method. Here is my code so far:

public static Array[] generateFirstArray(int seedValue)
{
    int[] firstArray = new int[20];
    Random randomNumber = new Random(seedValue);

    for (int i = 0; i < firstArray.Length; i++)
    {
        firstArray[i] = randomNumber.Next(0, 4);
    }

    return firstArray;
}

But when I run it, I get the following error:

Error 1 Cannot implicitly convert type 'int[]' to 'System.Array[]'

I tried to add [] after firstArray but still not working.

like image 397
Filipe Barreto Peixoto Teles Avatar asked Nov 28 '25 00:11

Filipe Barreto Peixoto Teles


2 Answers

Your return type is currently an array of Array objects. Change your return type to an array of ints (int[]):

public static int[] generateFirstArray(int seedValue)
like image 183
D Stanley Avatar answered Nov 30 '25 14:11

D Stanley


The signature of your methods says you're trying to return an Array of Array (Array[]).

You want to return an int[] instead so just change your signature to

public static int[] generateFirstArray(int seedValue)
like image 30
Justin Lessard Avatar answered Nov 30 '25 16:11

Justin Lessard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!