I have a 2D array, that I fill randomly with numbers. The code I have for this works fine, however, to organise my code better I'm wanting to put the "fill it randomly with numbers" part into a method.
The array is created from the Main() method, as I plan on passing and returning the array to/from other methods that will manipulate it. I then tried to write the method for filling the array, but I'm unsure how to either pass a multidimensional array, or return one either. According to MSDN I need to use an "out" rather than a return.
This is what I've tried so far:
static void Main(string[] args)
{
int rows = 30;
int columns = 80;
int[,] ProcArea = new int[rows, columns];
RandomFill(ProcArea[], rows, columns);
}
public static void RandomFill(out int[,] array, int rows, int columns)
{
array = new int[rows, columns];
Random rand = new Random();
//Fill randomly
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
if (rand.NextDouble() < 0.55)
{
array[r, c] = 1;
}
else
{
array[r, c] = 0;
}
}
}
These are the errors I have:
"The best overloaded method match for 'ProcGen.Program.RandomFill(out int[*,*], int, int)' has some invalid arguments"
"Argument 1: cannot convert from 'int' to 'out int[*,*]'"
What am I doing wrong, and what can I do to fix these errors? Also, am I right in thinking, because I'm using "out" that all I need to do is:
RandomFill(ProcArea[], rows, columns);
instead of?:
ProcArea = RandomFill(ProcArea[], rows, columns);
Is there a proper way of calling the method?
There is no need of an out parameter in your code.
Arrays are passed by reference
until, in the method, you initialise it with a new reference.
So, in your method, if you don't initialise it with a new reference, then you can go without using the out
parameter and values will be reflected in the original array -
public static void RandomFill(int[,] array, int rows, int columns)
{
array = new int[rows, columns]; // <--- Remove this line since this array
// is already initialised prior of calling
// this method.
.........
}
Try:
RandomFill(out ProcArea, rows, columns);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With