For some reason, this doesn't edit the size of the array inputted into it, and the data isn't added to the array inputted.
public static void RandomizeArray(int[] array)
{
int intRead;
int intReadSeed;
Random randomNum = new Random();
Console.WriteLine("How many ints do you want to randomly generated?");
intRead = Convert.ToInt32(Console.ReadLine());
array = new int[intRead];
Console.WriteLine("What's the maximum value of the randomly generated ints?");
intReadSeed = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < intRead; i++)
{
array[i] = (randomNum.Next(intReadSeed));
}
Console.WriteLine("Randomization Complete.\n");
}
2 Answers 2
When you pass array to this method, you pass it by value - that is, you make a brand new variable that ALSO points to the same object. If you edit the variable array in your method to point to a new array, it doesn't also make the other variable point to your new array - it still points to the old array. So when you return you haven't done any edits to the array that was passed in.
To fix this, return array; at the end of the method, and change the signature from void to int[]. Or you can do out int[] array as the parameter, so you pass by reference and edit over it.
3 Comments
out instead of ref, as Romoku suggests in his answer.return instead of out. out is usually only used in the case of 'returning' more than one thing from the method.Simple fix declare the parameter as out.
public static void RandomizeArray(out int[] array)
{
int intRead;
int intReadSeed;
Random randomNum = new Random();
Console.WriteLine("How many ints do you want to randomly generated?");
intRead = Convert.ToInt32(Console.ReadLine());
array = new int[intRead];
Console.WriteLine("What's the maximum value of the randomly generated ints?");
intReadSeed = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < intRead; i++)
{
array[i] = (randomNum.Next(intReadSeed));
}
Console.WriteLine("Randomization Complete.\n");
}
That way you can call it:
int[] array;
RandomizeArray(out array);
However, it would probably be better to simply return an array.
public static int[] GenerateRandomizedArray()
{
int intRead;
int intReadSeed;
Random randomNum = new Random();
Console.WriteLine("How many ints do you want to randomly generated?");
intRead = Convert.ToInt32(Console.ReadLine());
var array = new int[intRead];
Console.WriteLine("What's the maximum value of the randomly generated ints?");
intReadSeed = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < intRead; i++)
{
array[i] = (randomNum.Next(intReadSeed));
}
Console.WriteLine("Randomization Complete.\n");
return array;
}
randomNum.Next(intReadSeed + 1), otherwise the maximum value will be one less thanintReadSeed.