Search code examples
c#methodsdelegates

Is it possible to pass a method of another class to a function?


I have a 2D cell array(Cell[,] _map) and methods:

private void OpenNearCells(Vector2Int cellCoordinates)
{
    for (int i = cellCoordinates.Y - 1; i <= cellCoordinates.Y + 1; i++)
    {
        for (int j = cellCoordinates.X - 1; j <= cellCoordinates.X + 1; j++)
        {
            if (i < 0 || j < 0 || i >= Height || j >= Width)
                continue;

            _map[i, j].Open();
        }
    }
}

and:

private void NotifyNearCells(Vector2Int bombCoordinates)
{
    for (int i = bombCoordinates.Y - 1; i <= bombCoordinates.Y + 1; i++)
    {
        for (int j = bombCoordinates.X - 1; j <= bombCoordinates.X + 1; j++)
        {
            if (i < 0 || j < 0 || i >= Height || j >= Width)
                continue;

            _map[i, j].Notify();
        }
    }
}

Vector2Int is just a structure containing fields for the x and y coordinates.

I know about delegates a little, but my methods (Cell.Open and Cell.Notify) are in another class and they need to do some actions with the specific member of the class. So I want to do smth like this:

private void DoNearCellsAction(Function action, Vector2Int centerCellCoordinates)
{
    for (int i = cellCoordinates.Y - 1; i <= cellCoordinates.Y + 1; i++)
    {
        for (int j = cellCoordinates.X - 1; j <= cellCoordinates.X + 1; j++)
        {
            if (i < 0 || j < 0 || i >= Height || j >= Width)
                continue;

            _map[i, j].action();
        }
    }
}

Is it somehow possible to create a method like this or is it exist another way to avoid repeating code? What does this syntax look like?


Solution

  • Yes, this is possible. Taking a simplified version of your class:

    public class Cell 
    {
       public void Notify(Vector2Int vector) { }
       public void Open(Vector2Int vector) { }
    }
    

    You could create Actions of the same signature that house those:

    Action<Cell, Vector2Int> notifyAction = (cell, vector) => cell.Notify(vector);
    Action<Cell, Vector2Int> openAction = (cell, vector) => cell.Open(vector);
    

    Then your method would look something like:

    private void DoNearCellsAction(Action<Cell, Vector2Int> action, Vector2Int centerCellCoordinates)
    {
        action(_map[i, j], centerCellCoordinates)
    }