Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Generic Method passed as arguement, Argument type 'bool' is not assignable to parameter type 'System.Func<bool>'

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading