I am attempting to create a generic array iterator which goes iterates through a multidimensional array assigning each element with the result of a function.
When trying the following code I get the Error:
Argument type ‘bool’ is not assignable to parameter type ‘System.Func’
I would very much like to understand where I’m going wrong.
private InitialiseGame()
{
_grid = new Grid();
if (this._gameOfLifeGrid == null)
{
_gameOfLifeGrid = new bool[_grid.x,_grid.y];
IterateThroughArray(_gameOfLifeGrid, GetRandomBool());
}
if (this._neighbours == null)
{
_neighbours = new int[_grid.x,_grid.y];
}
}
private static bool GetRandomBool()
{
return _random.Next(0, 1) > 0;
}
public void IterateThroughArray<T>(T[,] array, Func<T> myAction)
{
for (var x = 0; x < array.GetLength(0); x++)
{
for (var y = 0; x < array.GetLength(0); y++)
{
array[x,y] = myAction();
}
}
}
Expecting a boolean result to work with the code however rider shows the error as written.
>Solution :
The problem is here
var _gameOfLifeGrid = new bool[5, 5];
IterateThroughArray(_gameOfLifeGrid, GetRandomBool()); // Notice the "()" after GetRandomBool
Simply put, you are calling the GetRandomBool function instead of passing it to your generic function. Therefore, you are actually passing the result of GetRandomBool instead of GetRandomBool itself.
Here is the corrected code:
private InitialiseGame()
{
_grid = new Grid();
if (this._gameOfLifeGrid == null)
{
_gameOfLifeGrid = new bool[_grid.x,_grid.y];
IterateThroughArray(_gameOfLifeGrid, GetRandomBool); // Remove "()" here
}
if (this._neighbours == null)
{
_neighbours = new int[_grid.x,_grid.y];
}
}