C#, returning an array in a function

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.

Upvotes: 2

Views: 185

Answers (3)

AlwaysAProgrammer
AlwaysAProgrammer

Reputation: 2919

the return type of your method must be int[] and not Array[]

Here is one more way of implementing it

int Min = 0;
int Max = 4;
Random randNum = new Random(seedValue);
int[] firstArray = Enumerable
                   .Repeat(0, 20)
                   .Select(i => randNum.Next(Min, Max))
                   .ToArray();
return firstArray;

Upvotes: 0

Justin Lessard
Justin Lessard

Reputation: 11901

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)

Upvotes: 6

D Stanley
D Stanley

Reputation: 152521

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)

Upvotes: 13

Related Questions